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

偶尔善良 提交于 2019-12-12 04:38:49

问题


I have this below span div and I copy this to another place in the DOM. But the onclick function I need to remove and place another onclick function.

<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')"


回答1:


Consider a sample HTML page:

<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

//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);



回答2:


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);



回答3:


document.getElementById("abc").onclick = function (){checkNodes('childNode1');}


来源:https://stackoverflow.com/questions/18331270/remove-and-replace-another-onclick-function-in-a-div-through-pure-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!