获取使用jQuery元素的所有属性 [英] Get all attributes of an element using jQuery

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

问题描述

我试图去通过一个元素,获得该元素的输出它们,例如一个标签可以有3个或更多的属性,未知的所有属性给我,我需要得到这些属性的名称和值。

I am trying to go through an element and get all the attributes of that element to output them, for example an tag may have 3 or more attributes, unknown to me and I need to get the names and values of these attributes. I was thinking something along the lines of:

$(this).attr().each(function(index, element) {
    var name = $(this).name;
    var value = $(this).value;
    //Do something with name and value...
});

谁能告诉我,如果这甚至有可能,如果是什么正确的语法会是什么?

Could anyone tell me if this is even possible, and if so what the correct syntax would be?

推荐答案

属性属性包含所有这些:

$(this).each(function() {
  $.each(this.attributes, function() {
    // this.attributes is not a plain object, but an array
    // of attribute nodes, which contain both the name and value
    if(this.specified) {
      console.log(this.name, this.value);
    }
  });
});


你也可以做的是延长什么

.attr ,这样就可以把它像 .attr()来获得所有属性的纯对象:


What you can also do is extending .attr so that you can call it like .attr() to get a plain object of all attributes:

(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);

用法:

var $div = $("<div data-a='1' id='b'>");
$div.attr();  // { "data-a": "1", "id": "b" }

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

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