我想用id="custom-taxonomy"向元素的onChange属性添加一个函数。我不想编辑这个文件。我想要一个javascript解决方案。
我的想法是通过id找到元素,然后添加函数。我怎样才能实现这个想法?
代码:
<div id ="custom-taxonomy">PRODUCT PRICES</div>预期结果:
<div id ="custom-taxonomy" name="custom-product" onchange="return chothuephuongxa();>PRODUCT PRICES</div>发布于 2019-03-27 17:17:20
您可以使用setAttribute()和document.getElementById来完成此操作
let elm = document.getElementById('custom-taxonomy')
elm.setAttribute('name',"custom-product")
elm.setAttribute("onclick","return chothuephuongxa();")
console.log(elm.outerHTML)<div id ="custom-taxonomy">PRODUCT PRICES</div>
便笺
<div>的name属性,而是使用elm.name = ...,因为name属性在<div>元素上不可用。同样,
elm.onclick = "return chothuephuongxa();"也不正确,因为这会将事件设置为string,而不是function发布于 2019-03-27 17:14:31
您可以使用setAttribute向元素添加属性:
document.getElementById('custom-taxonomy').setAttribute('name', 'custom-product');对于您的事件也可以这样做。
https://stackoverflow.com/questions/55373437
复制相似问题