2

Possible Duplicate:
check window open

I'm using JQuery to change the URL of a window.open event depending on certain selections:

$(".class").click(function() {
    window.open("http://www.url.com/" + variable);
});

The problem is that every time it changes, I have to call this click function again and the old window.open event is still remembered and two windows are opened, then 3, then 4, etc.

I have tried a lot of work-arounds and nothing is working. I tried calling the click function just once and then changing the variable but the window.open will only remember the original variable.

Is there a way to remove old click event handlers before adding a new one?

4

3 に答える 3

1

The reason changing the variable doesn't work is because of variable scope: the anonymous function inherits the scope of its original context, regardless of what has happened since then. You have two potential answers:

Bad: use a global variable (window.variable) instead.

Good: Set the window.open function to a variable itself:

WindowOpener = $(".class").click(function() {
    window.open("http://www.url.com/" + variable);
});

and then

WindowOpener.unbind();

to clear the prior event whenever you need. Jamey Sharp's answer is also correct, and will likely work in your scenario unless you're doing something unusual with the bound element.

于 2012-11-14T00:11:32.067 に答える
0

look at $.unbind -- http://api.jquery.com/unbind/ .You can use that to remove your old event

于 2012-11-14T00:10:24.323 に答える
0

Before adding the new click handler, you can remove the old one(s):

$(".class").unbind('click');
于 2012-11-14T00:11:01.583 に答える