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函数(不是单击时)?


基础教程推荐
- 如何添加到目前为止的天数? 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01