我正在寻找一种使用jQuery或Vanilla JS获取以“ on”开头的元素的所有属性的方法。我目前正在获取所有属性,然后使用@primvdb在本文中提出的方法遍历它们以获得我想要的属性:使用jQuery获取元素的所有属性。
我的代码如下所示:
/* Expanding .attr as proposed by @primvdb */
(function(old) {
$.fn.attr = function() {
if(arguments.length === 0) {
if(this.length === 0) {
return null;
}
var obj = {};
$.each(this[0].attributes, function() {
if(this.specified) {
obj[this.name] = this.value;
}
});
return obj;
}
return old.apply(this, arguments);
};
})($.fn.attr);
/* And then my function */
$.fn.attrThatBeginWith = function(begins){
var attributes = this.attr();
var attrThatBegin = {};
for(var attr in attributes){
if(attr.indexOf(begins)==0){
attrThatBegin[attr] = attributes[attr];
}
}
return attrThatBegin;
};
/* Usage */
var onAttributes = $("#MyElement").attrThatBeginWith("on");
这是可行的,但非常“肮脏”。似乎对于jQuery的所有广泛功能,应该有一种更好的“更清洁”的方式来执行此操作。有人有什么建议吗?
您可以使用来将所有属性附加到元素上element.attributes
。
可以将本机属性对象转换为数组,然后根据给定的字符串进行过滤。
执行上述操作的插件如下所示
$.fn.attrThatBeginWith = function(begins){
return [].slice.call(this.get(0).attributes).filter(function(attr) {
return attr && attr.name && attr.name.indexOf(begins) === 0
});
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句