2016-05-01 32 views
1

我正在寻找一种方法来获取以“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的所有巨大功能似乎都应该有一个更好的“更干净”的方式来做到这一点。有人有任何建议吗?

+1

为什么你需要吗?你可以获得所有的本地属性,但并不是jQuery支持的所有东西,因为on()也可以处理自定义事件等。 – adeneo

+0

我需要知道元素具有的“on”属性。如果HTML有一个不受支持的“on”属性,那就不是我关心的问题。 –

+0

如果有效,它可能更适合[代码评论](http://codereview.stackexchange.com/) – adeneo

回答

3

您可以使用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 
    }); 
}; 

FIDDLE

+0

这很好,除了我希望它可以是一个对象而不是一个数组。 –

+0

不知道为什么你想要一个对象,但你可以做一个 - > https://jsfiddle.net/yvs7uczx/2/ – adeneo

+0

真棒谢谢。 –

相关问题