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

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

推荐答案

attributes属性包含以下所有内容:

$(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()一样调用它,以获得所有属性的普通对象:

(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相关问答推荐

如何通过Juser-row-num添加动态值

这是否会导致内存泄漏?

逐个交换图像

jQueryUI 模态对话框不显示关闭按钮 (x)

如何从 onclick div 属性检测 Javascript 中的 control+click?

自动完成时触发的任何事件?

如何在jQuery中 Select 具有特定ID的所有元素?

验证外部脚本是否已加载

使用 jquery/ajax 刷新/重新加载 Div 中的内容

在完成前一个请求之前中止新的 AJAX 请求

Jquery .show() 不显示隐藏可见性的 div

如何在 Angular 4 中使用 jQuery 插件?

使用 jQuery 获取 div 的可见高度

如何在新窗口中打开链接?

图片转Base64

jQuery: Select 不为空的数据属性?

通过 AJAX MVC 下载 Excel 文件

jquery - 从一个非常大的表中删除所有行的最快方法

.success() 和 .complete() 之间的区别?

jquery $(window).height() 正在返回文档高度