婷婷同學_
2019-12-07 14:07:18
我試圖創建一個看起來和感覺像<a>標簽項的鏈接,但運行一個函數而不是使用href。當我嘗試將onclick函數應用于鏈接時,無論該鏈接從未被單擊過,它都會立即調用該函數。此后任何嘗試單擊鏈接的嘗試都會失敗。我究竟做錯了什么?的HTML<div id="parent"> <a href="#" id="sendNode">Send</a></div>Java腳本startFunction();function secondFunction(){ window.alert("Already called!?");}function startFunction() { var sentNode = document.createElement('a'); sentNode.setAttribute('href', "#"); sentNode.setAttribute('onclick', secondFunction()); //sentNode.onclick = secondFunction(); sentNode.innerHTML = "Sent Items"; //Add new element to parent var parentNode = document.getElementById('parent'); var childNode = document.getElementById('sendNode'); parentNode.insertBefore(sentNode, childNode);}如您所見,我嘗試了兩種添加此onclick函數的不同方法,兩種方法都具有相同的效果。
1 回答

梵蒂岡之花
TA貢獻1900條經驗 獲得超5個贊
你要 .onclick = secondFunction
不 .onclick = secondFunction()
后者調用(執行),secondFunction而前者secondFunction在onclick事件傳遞給要調用的的引用
function start() {
var a = document.createElement("a");
a.setAttribute("href", "#");
a.onclick = secondFunction;
a.appendChild(document.createTextNode("click me"));
document.body.appendChild(a);
}
function secondFunction() {
window.alert("hello!");
}
start();
您也可以使用elem#addEventListener
a.addEventListener("click", secondFunction);
// OR
a.addEventListener("click", function(event) {
secondFunction();
event.preventDefault();
});
添加回答
舉報
0/150
提交
取消