立即调用 Javascript onclick 函数(不是单击时)?

IT技术 javascript html onclick
2021-01-22 11:28:11

我正在尝试创建一个链接,它的外观和感觉就像一个<a>标签项,但运行一个函数而不是使用 href。

当我尝试将 onclick 函数应用于链接时,它会立即调用该函数,而不管链接从未被单击过。此后任何点击链接的尝试都失败了。

我究竟做错了什么?

HTML

<div id="parent">
    <a href="#" id="sendNode">Send</a>
</div>

Javascript

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

JsFiddle

如您所见,我尝试了两种不同的方法来添加这个 onclick 函数,这两种方法都具有相同的效果。

1个回答

你要 .onclick = secondFunction

不是 .onclick = secondFunction()


后者调用(执行),secondFunction而前者传递secondFunctiononclick事件的调用的引用


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();
});
@leigero — JS Fiddle 中的代码与此答案中的代码不匹配
2021-03-13 11:28:11
@leigero 是的,它确实有效。请参阅附加的代码段。
2021-03-13 11:28:11
@leigero:当然你的小提琴不起作用。然而,答案是有效的。
2021-03-22 11:28:11
谢谢。愚蠢的错误,只是通过尝试在 JsFiddle 中解决问题而变得复杂。
2021-03-31 11:28:11