Javascript的object.onClick运行函数而不是设置onClick,如何防止这种情况发生并只执行onClick函数?
我有以下代码:
function sdefaults()
{
alert("test");
}
var btnpos, sbtn;
btnpos = document.getElementsByName('somePosition')[0];
sbtn = document.createElement('input');
btnpos.parentNode.insertBefore(sbtn, btnpos.nextSibling);
sbtn.type = "button";
sbtn.name = "social";
sbtn.value = "Defaults";
sbtn.onClick = sdefaults();
按钮出现在我想要的位置,并且名称/值设置正确。但是,当我加载页面时,sdefaults()
函数会运行,然后如果我单击该按钮,则不会发生任何情况。任何人都可以提供有关如何防止该函数在负载上运行并强制其仅在单击时运行的见解吗?
谢谢
I have the following code:
function sdefaults()
{
alert("test");
}
var btnpos, sbtn;
btnpos = document.getElementsByName('somePosition')[0];
sbtn = document.createElement('input');
btnpos.parentNode.insertBefore(sbtn, btnpos.nextSibling);
sbtn.type = "button";
sbtn.name = "social";
sbtn.value = "Defaults";
sbtn.onClick = sdefaults();
The button appears where I want it to and the name/value are set correctly. However when I load the page, the sdefaults()
function is run and then if I click the button, nothing happens. Could anyone provide any insight into how to prevent the function from running on load and force it to only run onclick?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
更改
为:
sbtn.onClick = sdefaults();
表示:“运行sdefaults
函数并将结果存储在sbtn.onClick
中。< code>btn.onClick = sdefaults; 表示:“将
sbtn.onClick
设置为函数sdefaults
”,这就是您要查找的内容。Change:
to:
sbtn.onClick = sdefaults();
means: "Run thesdefaults
function and store the result insbtn.onClick
.btn.onClick = sdefaults;
means: "Setsbtn.onClick
to the functionsdefaults
", which is what you're looking for.您必须了解函数引用和函数调用之间的区别。
考虑以下函数
现在,让我们看一下引用该函数的一些示例。为了引用一个函数,我们使用它的符号名称,就像任何其他变量一样。
现在我们将考虑函数调用。这意味着该函数执行并且其返回值被发送回调用范围。
现在,完全可以通过更改
sdefaults()
的代码来修改您的代码片段。这就是它的样子。现在,当您执行
sbtn.onClick = sdefaults();
时,onClick
属性会收到它所期望的函数,因为我们已将 sdefaults 修改为实际上没有警报“test”,但返回一个匿名函数,该函数本身会警报“test”。 (顺便说一句,这种特定技术通常称为 lambda 或委托函数)希望能够澄清这一点。
You have to understand the difference between function referencing, and function invocation.
Consider the following function
Now, lets look at some samples of referencing this function. To reference a function, we use its symbol name, just like any other variable.
Now we'll consider function invocation. This means the function executes and its return value is sent back to the calling scope.
Now, it's entirely possible to modify your code snippet just by changing the code of
sdefaults()
. Here's how that would look.Now, when you execute
sbtn.onClick = sdefaults();
what happens is theonClick
property receives what its expecting, a function, since we've modified sdefaults to not actually alert "test", but to return an anonymous function which itself will alert "test". (As a side note, this specific technique is commonly called a lambda or delegate function)Hope that clears it up.