首页 > 解决方案 > 仅在单击事件上将每个按钮或锚属性作为 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 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));

这工作正常,但唯一的问题是我希望此代码仅适用于点击事件。

任何人都可以在这里帮助我如何在每个按钮和锚标签上设置点击事件。

提前致谢。

标签: javascript

解决方案


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

const getAttributes = (el) => {
  let val = el.outerHTML;
  val = val.slice(val.indexOf(' ')+1, val.indexOf('>'))
           .split(' ')
           .reduce((a,v) => {
              const [key, value] = v.split('=');
              a.attributes[key] = value.replace("\"", '').replace("\"", ''); // Need a regex here.
              return a;
            }, {"attributes" : {}});
  return val;
}

document.addEventListener('click', (event) => {
  //console.log (event.target.attributes);
  if(event.target.matches('a, div, button')) {
    console.log(getAttributes(event.target));
  }
});
<a href="#" div="mydiv" class="myclass" layer="mylayer">Test</a>
<button type="button" name="button" value="btnValue" id="btn">Test</button>


推荐阅读