开发者

JavaScript function calling from link click

I have a piece of JS code as follows:

window.onbeforeunload = function saveFav() {
//Some JS code
}

Now this same function needs to be called from a link click handler, so I am just directly calling the function as:

$("#someLink").click(function() {
   saveFav();
});

But for some reasons saveFav() is not gettin开发者_StackOverflow中文版g called from link click. Is there some syntax issue OR will the function be called only on page unload?

I do not want to replicate the code as it is same on both unload and link click.

Please help me.


Really simple, define the function once like so:

function saveFav() {
   //...
}

Then assign it to the appropriate handlers:

window.onbeforeunload = saveFav;
$("#someLink").click(saveFav);

The reasoning behind why your code does not work is because creating a named function expression does not create a symbol in the current scope with the function's name, rather the name only exists within the scope of the function itself, for the sole purpose of the function to have the ability to call itself recursively.


You just want to define your function, and then assign it to both:

function saveFav() {
  //Some JS code
}

window.onbeforeunload = saveFav;
$("#somelink").click( saveFav );

You can of course assign either of these events to call an anonymous function which does some other stuff, and then calls saveFav, but it is not necessary to define an anonymous function that only calls saveFav.


You should define your saveFav function before assigning it to onbeforeunload if you want to call it in this way.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜