繁体   English   中英

通过Pure Javascript删除并替换div中的另一个onclick函数?

[英]Remove and replace another onclick function in a div through Pure Javascript?

我在span div下面有这个,并将其复制到DOM中的另一个位置。 但是我需要删除onclick函数并放置另一个onclick函数。

<span class="plus childNode1" onclick="expand_collapseChildnodes('childNode1')" id="abc"></span>

在这里,我必须删除复制元素的onclick =“ expand_collapseChildnodes('childNode1')”并将其替换为onclick =“ checkNodes('childNode1')”

考虑一个示例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>

现在将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/

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM