Javascript 仅在单击事件时将每个按钮或锚属性作为json字符串获取

Javascript 仅在单击事件时将每个按钮或锚属性作为json字符串获取,javascript,Javascript,我试图在每个按钮上以json字符串的形式获取所有属性值,并在单击事件中锚定元素 像这样 <a href="test.html" div="mydiv" class="myclass" layer="mylayer"></a> <button type="button" name="button" value="btnValue" id="btn"></button> { "attributes": {

我试图在每个按钮上以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 elements = document.querySelectorAll('button, a');
var elementAttributes = [];
elements.forEach(function(el){
  var attrs = {attributes:{}};
   for(var i=0; i<el.attributes.length; i++) {
     attrs.attributes[el.attributes[i].name] = el.attributes[i].value;
   }
  elementAttributes.push(attrs);
});

console.log(JSON.stringify(elementAttributes));
这是工作良好,但唯一的问题是我想这段代码是工作,只有在点击事件

这里有人能帮我吗?我如何在每个按钮和锚定标签上设置点击事件


提前感谢。

这有点粗糙,但它将提取书面属性,而不是在HTMLElement.attributes下找到的大量集合

const getAttributes=el=>{ 设val=el.outerHTML; val=val.sliceval.indexOf'+1,val.indexOf'>' .拆分“ .reducea,v=>{ 常量[key,value]=v.split'='; a、 attributes[key]=value.replace\,.replace\,;//此处需要正则表达式。 返回a; },{属性:{}; 返回val; } document.addEventListener“单击”,事件=>{ //console.log event.target.attributes; ifevent.target.matches'a,div,button'{ console.LogGetAttributeEvent.target; } };
你是否因为其他原因问了与4小时前相同的问题?