我正在寻找一种方法来获取以“on”开头的元素的所有属性,使用jQuery或Vanilla JS。我目前得到所有属性,然后通过它们循环使用@primvdb在此帖子中提出的方法来获取我想要的:Get all attributes of an element using jQuery。我可以使用jquery获得以“on”开头的所有属性吗?
我的代码如下所示:
/* 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的所有巨大功能似乎都应该有一个更好的“更干净”的方式来做到这一点。有人有任何建议吗?
为什么你需要吗?你可以获得所有的本地属性,但并不是jQuery支持的所有东西,因为on()也可以处理自定义事件等。 – adeneo
我需要知道元素具有的“on”属性。如果HTML有一个不受支持的“on”属性,那就不是我关心的问题。 –
如果有效,它可能更适合[代码评论](http://codereview.stackexchange.com/) – adeneo