Javascript onclick function is called immediately (not when clicked)?(立即调用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函数(不是单击时)?


- 失败的 Canvas 360 jquery 插件 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01