首页 > 解决方案 > 在单击事件javascript上将每个按钮或锚属性作为json字符串获取

问题描述

我正在尝试将所有属性值作为每个按钮上的 json 字符串和单击事件上的锚元素。

像这样。

<a href="test.html" div="mydiv" class="myclass" layer="mylayer"></a>
<button type="button" name="button" value="btnValue" id="btn"></button>

    {
        "attributes": {
             "href": "test.html",
             "div": "mydiv",
             "class": "myclass",
             "layer": "mylayer"
        }
    }

{
    "attributes": {
        "type": "button",
        "name": "button",
        "value": "btnValue",
        "id": "btn"
    }
}

这是我的代码js代码

var attr = document.querySelectorAll('button, a');
for (var i = 0;i < attr.length;i++){
    attr[i].addEventListener('click',function(){
        console.log(attr);
      });
}

谁能帮我解决这个问题我怎么能做到这一点?

提前致谢。

标签: javascript

解决方案


尝试

var elements = document.querySelectorAll('button, a');
elements.forEach(function (el) {
  el.addEventListener('click', function(e) {
    e.preventDefault();
    var attrs = {attributes:{}};
    for(var i=0; i<e.currentTarget.attributes.length; i++) {
      attrs.attributes[e.currentTarget.attributes[i].name] = e.currentTarget.attributes[i].value;
    }
    console.log(JSON.stringify(attrs));
  });
});

推荐阅读