[英]Remove and replace another onclick function in a div through Pure Javascript?
I have this below span div and I copy this to another place in the DOM. 我在span div下面有这个,并将其复制到DOM中的另一个位置。 But the onclick function I need to remove and place another onclick function.
但是我需要删除onclick函数并放置另一个onclick函数。
<span class="plus childNode1" onclick="expand_collapseChildnodes('childNode1')" id="abc"></span>
Here I have to remove the onclick="expand_collapseChildnodes('childNode1')" for the copied element and replace it with onclick="checkNodes('childNode1')" 在这里,我必须删除复制元素的onclick =“ expand_collapseChildnodes('childNode1')”并将其替换为onclick =“ checkNodes('childNode1')”
Consider a sample HTML page: 考虑一个示例HTML页面:
<html>
<head>
</head>
<body>
<div id ="d1">
<span class="plus childNode1" onclick="expand_collapseChildnodes('childNode1')" id="abc"></span>
</div>
<div id ="d2">
</div>
</body>
</html>
Now to move the element with id abc from DOM element with id d1 to another with id d2 现在将ID为abc的元素从ID为d1的 DOM元素移动到另一个ID为d2的元素
//get the element
var element = document.getElementById("abc");
//detach from source
document.getElementById("d1").removeChild(element);
//remove onclick attribute
element.removeAttribute("onclick");
//add the modified attribute
element.setAttribute("onclick", "sampleFunc()");
//attach the element to another source
document.getElementById("d2").appenChild(element);
http://jsfiddle.net/KvnKZ/1/ http://jsfiddle.net/KvnKZ/1/
var div=document.getElementsByTagName("div");
var span=document.getElementById("abc");
var newSpan=span.cloneNode(true);
newSpan.setAttribute("id","newID"); //change id
newSpan.setAttribute("onclick","myFunc()"); //change onclick event handler
div[0].appendChild(newSpan);
document.getElementById("abc").onclick = function (){checkNodes('childNode1');}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.