使用jQuery获取元素的所有属性

Get all attributes of an element using jQuery(使用jQuery获取元素的所有属性)

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

问题描述

我正在尝试遍历一个元素并获取该元素的所有属性以输出它们,例如,一个标签可能有 3 个或更多属性,我不知道,我需要获取这些属性的名称和值.我的想法是这样的:

$(this).attr().each(function(index, element) {var name = $(this).name;var 值 = $(this).value;//用名称和值做一些事情...});

谁能告诉我这是否可行,如果可行,正确的语法是什么?

解决方案

attributes 属性包含所有这些:

$(this).each(function() {$.each(this.attributes, function() {//this.attributes 不是一个普通的对象,而是一个数组//属性节点,包含名称和值如果(this.specified){console.log(this.name, this.value);}});});

<小时>

您还可以做的是扩展 .attr 以便您可以像 .attr() 一样调用它来获取所有属性的普通对象:

(函数(旧) {$.fn.attr = 函数() {if(arguments.length === 0) {如果(this.length === 0){返回空值;}变量 obj = {};$.each(this[0].attributes, function() {如果(this.specified){obj[this.name] = this.value;}});返回对象;}返回 old.apply(this, arguments);};})($.fn.attr);

用法:

var $div = $("

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?

解决方案

The attributes property contains them all:

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


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

Usage:

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

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

本文标题为:使用jQuery获取元素的所有属性

基础教程推荐