lei*_*ero 0 html javascript onclick
我试图创建一个看起来和感觉像<a>标签项的链接,但运行一个函数而不是使用href。
当我尝试将onclick函数应用于链接时,无论该链接从未被单击过,它都会立即调用该函数。此后任何尝试单击链接的尝试都会失败。
我究竟做错了什么?
的HTML
<div id="parent">
<a href="#" id="sendNode">Send</a>
</div>
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我尝试了两种添加此onclick函数的不同方法,两种方法都具有相同的效果。
你要 .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();Run Code Online (Sandbox Code Playgroud)
您也可以使用elem#addEventListener
a.addEventListener("click", secondFunction);
// OR
a.addEventListener("click", function(event) {
secondFunction();
event.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)