簡體   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