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函数(不是单击时)?
基础教程推荐
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 直接将值设置为滑块 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01