是否可以仅按属性值选择元素?
我需要使用jquery仅按属性value
(忽略键)查找页面中的所有元素。
有没有办法轻松做到这一点?
目前,我只是迭代页面中的所有元素,每个属性等。
你可以使用$.expr
, Element.attributes
, Array.prototype.some()
$.expr[":"].attrValue = function(el, idx, selector) { return [].some.call(el.attributes, function(attr) { return attr.value === selector[selector.length - 1] }) }; // filter element having attribute with `value` set to `"abc"` $(":attrValue(abc)").css("color", "blue");
abc def ghi jkl
使用括号[]
var ElementsWithAttributeKeyTest = $('[attributeKey="Test"]');
或者将具有属性名称和值作为参数的对象传递给此函数:
var getElemsByAttribute = function(obj) { if (obj) { if (obj.attributeKey && obj.attributeValue) { return $('[' + obj.attributeKey + '="' + obj.attributeValue + '"]'); } } } var attrObj = { attributeKey: 'data-color', attributeValue: 'red' } getElemsByAttribute(attrObj).css('color', 'red');
Red Red Green Blue Red Green
如果要搜索所有属性值,可以使用这个小插件:
$.fn.search_by_attr_value = function(regex) { return this.filter(function() { var found = false; $.each(this.attributes, function() { if (this.specified && this.value.match(regex)) { found = true; return false; } }); return found; }); };
你可以像这样使用它:
$('*').search_by_attr_value(/^some value$/);
基于这个答案
你可以定义新函数take作为你想要过滤的值的参数(例如get_elements_by_value(filter)
),然后在这个函数内部使用$('*').each()
解析页面的所有元素,之后解析使用如下属性attributes
的那些元素的每个元素el
的attributes
:
$.each(el.attributes, function(){ })
然后在each
循环内部,您可以创建条件并将匹配的值与matched[]
内的传递filter
一起推送。
检查下面的工作示例,希望这有帮助。
function get_elements_by_value(filter){ var matched=[]; $('*').each(function(index,el) { $.each(el.attributes, function() { if( this.value===filter ) matched.push(el); }) }) return $(matched); } get_elements_by_value('my_value').css('background-color','green');
AA BB DD
EE