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 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) => {
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>
推荐阅读
- python - 正确实现 asyncio
- javascript - React 前端项目中的 Yelp API(融合)
- unit-testing - React Native Expo App:如何让它运行 Jest 测试
- ruby-on-rails - 全局变量被覆盖
- r - 在每张 Xaringan 幻灯片中包含上一个/下一个链接
- r - 如何在 Centos 中使用 tail -f 监控目录并包含新文件(用于 Docker 中的闪亮服务器日志)
- r - 更改ggplot中图形的颜色
- cocoa - 防止用户更改 Cocoa 应用程序创建的目录的权限
- unix - AWK - 使用 substr 时 printf 和 sprintf 之间的奇怪区别
- python - Pytest 固定装置范围