我正在尋找一種方法來獲取以「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