我可以获取所有以"on"开头的属性吗?使用jQuery的? [英] Can i get all attributes that begin with "on" using jquery?

查看:90
本文介绍了我可以获取所有以"on"开头的属性吗?使用jQuery的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种使用jQuery或Vanilla JS获取以"on"开头的元素的所有属性的方法.我目前正在获取所有属性,然后使用@primvdb在本文中提出的方法遍历它们以获得我想要的属性:

I am looking for a way to get all the attributes of an element that begins with "on" using jQuery or Vanilla JS. I am currently getting all attributes and then looping through them to get the ones I want using the method proposed by @primvdb on this post: Get all attributes of an element using 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的所有广泛功能,应该有一种更好的更清洁"的方式来执行此操作.有人有什么建议吗?

And this works but is very "dirty". It's seems like with all the vast features of jQuery there should be a better "cleaner" way to do this. Does anybody have any suggestions?

推荐答案

您可以使用element.attributes获取附加到元素的所有属性.
可以将本机属性对象转换为数组,然后根据给定的字符串进行过滤.

You can get all attributes attached to an element with element.attributes.
The native attributes object can be converted to an array and then filtered based on the given string.

执行上述操作的插件看起来像

A plugin that does the above would look like

$.fn.attrThatBeginWith = function(begins){
    return [].slice.call(this.get(0).attributes).filter(function(attr) {
        return attr && attr.name && attr.name.indexOf(begins) === 0
    });
};

FIDDLE

这篇关于我可以获取所有以"on"开头的属性吗?使用jQuery的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆