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

Javascript onclick function is called immediately (not when clicked)?(立即调用Javascript onclick函数(不是单击时)?)

本文介绍了立即调用Javascript onclick函数(不是单击时)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个链接,它的外观和感觉类似于 <a> 标记项,但运行的是函数而不是使用 href.

I am trying to create a link, which looks and feels like an <a> tag item, but runs a function instead of using the href.

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

When I try to apply the onclick function to the link it immediately calls the function regardless of the fact that the link was never clicked. Any attempt to click the link thereafter fails.

我做错了什么?

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 函数,两者的效果是一样的.

As you can see I tried two different ways of adding this onclick function, both of which have the same effect.

推荐答案

你想要.onclick = secondFunction

不是 .onclick = secondFunction()

后者调用(执行)secondFunction,而前者传递对 secondFunction 的引用以在 onclick 事件中调用

The latter calls (executes) secondFunction whereas the former passes a reference to the secondFunction to be called upon the onclick event

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

这篇关于立即调用Javascript onclick函数(不是单击时)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:立即调用Javascript onclick函数(不是单击时)?

基础教程推荐