javascript - 在单击事件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);
});
}
谁能帮我解决这个问题我怎么能做到这一点?
提前致谢。
解决方案
尝试
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));
});
});
推荐阅读
- spring - Spring Security 中的动态 RBAC 配置
- javascript - 如何将两个画布视频元素写入一个新画布
- tmux - minicom 输出在选择树上的 tmux 内消失
- c# - 将自定义筛选器属性单元测试从 .NET Framework 迁移到 .NET Core 2.1
- imagemagick - Transparent pattern tiling in Image Magick generates broken pattern
- python-3.x - 如何在 PonyORM 中“LEFT JOIN”的“ON”原因中添加条件
- apache-spark - 获取特征重要性 PySpark 朴素贝叶斯分类器
- c# - 如何格式化导出到 Excel 的 DataGridView 的背景?
- java - Is it a good idea to use datastax mapper to save thousands of records using saveAsync
- java - selenium webdriver没有使用apache poi将数据写入excel表