我知道[name^="value"]
选择器,但是是否有类似的选择器(或技术)可以查询以给定值开头的所有属性?
我正在寻找类似$("[*^='http://www.something.com']")
的东西(不存在)。
它将匹配包含至少一个属性的所有元素,其值以 http://www.something.com
开头。
说:
<img src="http://www.something.com/image.jpg" />
<a href="http://www.something.com">Something</a>
<link rel="stylesheet" href="http://www.something.com/css/style.css" type="text/css">
属性名称可以是任何东西,不仅仅是src
和href
,甚至是非标准属性。
有没有已知的方法可以做到这一点?
其他答案中的一些想法放在一起,并编写了一个自定义选择器。
选择器
$.expr[':'].hasAttrStartingWithValue = function (obj, index, meta) {
var startsWithAttrValue = false;
var value = meta[3];
for (var i = 0; i < obj.attributes.length; i++) {
var attr = obj.attributes[i];
// attr.value starts with value
if (attr.specified && attr.value.lastIndexOf(value, 0) === 0) {
startsWithAttrValue = true;
break;
}
}
return startsWithAttrValue;
};
它尚未经过适当的交叉浏览和正确性测试,我相信它可以进一步优化,但它似乎在 IE 11、FF 24 和 Chrome 32 上运行良好。
用法
// Logs every occurrence of a value in any attribute of the page
$(":hasAttrStartingWithValue('http://www.something.com')").each(function (i, e) {
console.log(i + " - " + e.outerHTML);
});
// Matches only children of test
$("#test :hasAttrStartingWithValue('http://www.something.com')")
.css('background-color', 'red');
工作小提琴。
function strstr (haystack, needle, bool) {
var pos = 0;
haystack += '';
pos = haystack.indexOf(needle);
if (pos == -1) {
return false;
} else {
if (bool) {
return haystack.substr(0, pos);
} else {
return haystack.slice(pos);
}
}
}
$( document ).ready(function(){
$('*').each(function() {
$.each(this.attributes, function() {
// this.attributes is not a plain object, but an array
// of attribute nodes, which contain both the name and value
if(this.specified) {
if( strstr(this.value,'http://') )
alert(this.name+'+'+this.value);
}
});
});
});
警报所有属性和值...
自定义此代码...
jsfiddle
如果你想为 img、a 和 link 标签做这件事,那么你可以这样做:
var ref = '"http://www.something.com"';
var elems = [].slice.call(document.querySelectorAll('img[src='+ref+'], a[href='+ref+'], link[href='+ref+']'));
//do something with the elems array
如果你想走另一条路...
JS在香草JS中工作可憎的小提琴
让我难过的代码(查询眼前的一切、循环中的循环、循环中的正则表达式等):
var rx = /(^http://www.something.com)/;
var loopAgain = function () {
for (var j = 0, leng = attrs.length; j < leng; j++) {
if (rx.test(attrs[j].value)) {
return true;
}
return false;
}
};
var allTheThings = [].slice.call(document.querySelectorAll('*'));
for (var i = 0, len = allTheThings.length; i < len; i++) {
var attrs = allTheThings[i].attributes;
if (loopAgain()) {
console.log(allTheThings[i]);
}
}