Javascript's object.onClick runs the function instead of setting onClick, how can I prevent that from happening and only execute the function onClick?
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 cli开发者_Python百科ck 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
Change:
sbtn.onClick = sdefaults();
to:
sbtn.onClick = sdefaults;
sbtn.onClick = sdefaults();
means: "Run the sdefaults
function and store the result in sbtn.onClick
.
btn.onClick = sdefaults;
means: "Set sbtn.onClick
to the function sdefaults
", which is what you're looking for.
You have to understand the difference between function referencing, and function invocation.
Consider the following function
function foo()
{
alert( 'Hello World' );
}
Now, lets look at some samples of referencing this function. To reference a function, we use its symbol name, just like any other variable.
// Alert contents of foo
alert( foo );
// Set foo as the click handler for the body
document.body.onclick = foo;
// Assign a new function to foo
foo = function(){ alert( 'Goodbye!' ); }
Now we'll consider function invocation. This means the function executes and its return value is sent back to the calling scope.
// Invoke foo simply
foo();
// Invoke foo with a specific scope
foo.apply( this ); // or foo.call( this );
Now, it's entirely possible to modify your code snippet just by changing the code of sdefaults()
. Here's how that would look.
function sdefaults()
{
return function()
{
alert("test");
}
}
Now, when you execute sbtn.onClick = sdefaults();
what happens is the onClick
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.
精彩评论