2017-07-27 40 views
0

我需要在整個DOM中搜索文本,但只想將搜索限制爲屬性(屬性)。如果你已經知道他們的名字,我只知道搜索屬性。例如:在整個DOM中搜索文本的所有屬性

$(document).find("[name='description']"); 

但我想是這樣的:

$(document).find("[*='description']"); 

回答

1

我不知道這是否是解決方案的最美麗的,因爲它需要你通過網頁上的所有元素循環,但你可以檢查所有元素的attributes財產。

$(function() { 
 
    $("*").each(function() { 
 
    var $el = $(this); 
 
    $.each(this.attributes, function() { 
 
     if (this.value=='description') { 
 
     console.log('Found for attribute "'+this.name+'".'); 
 
     console.log('Text: '+$el.text()); 
 
     } 
 
    }); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div data-test1="description">test1</div> 
 
<div data-test2="bla" id="description">test2</div> 
 
<div data-test3="bla bla" class="description">test3</div> 
 
<div data-test4="description" class="description">test4</div>

2

沒有一點魔法,我不知道這是否是可能的。

但是這裏有一個方法可以做一點點擴展。

$.expr[":"].FindAttrByValue = function(element, index, ElVal){ 
 
    var g = $(element.attributes).filter(function() { 
 
     return this.value === ElVal[3]; 
 
    }).length; 
 
    if (g > 0) { 
 
     return element; 
 
    } 
 
}; 
 
var e =$(document).find('*:FindAttrByValue("description")'); 
 
console.log(e.text())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div custom="description">test</div>