3

我有 2 个文件,文件 1 ( head.tpl) 包含这个默认函数操作

$(document).on("click", "#blackout", function(){
    closeSkyBox();
});

这是我要运行的默认操作,它可以工作。

在我的第二页上,我想覆盖其中的操作head.tpl

$(document).on("click", "#blackout", function(){
    closeSkyBox(function(){
        pev_for_country = '';
    });
});

所以,现在当我测试代码时,每个都运行,所以如果我要放置一个警报(出于测试原因),我会得到两个警报框。我怎样才能使它只有第二页中的一个运行,而其中的一个head.tpl被禁用。然后,当我不在第三页上覆盖它时,head.tpl运行中的那个?

4

3 回答 3

5

看起来你正在寻找jQuery 的 .off

$(document)
    .off('click', '#blackout')
    .on('click', '#blackout', function () {
        // ...
    });
于 2013-08-28T16:55:52.970 回答
1

You can use .off to remove all event handlers, but you should be cautious: what if other libraries add event handlers that you don't want to remove subscribe to this event? Also, if you add an additional event handler at a later date, this would obliterate it.

A better approach, I think, is to create a function that you can override:

function blackoutClick() {
    closeSkyBox();
}

And set up your click handler:

$(document).on("click", "#blackout", function(){
    blackoutClick();
});

Or, as Paul pointed out in the comments below, you don't even need to wrap that handler in an anonymous function, you can just use the cleaner:

$(document).on("click", "#blackout", blackoutClick );

Then, in your second page, you can just modify that function:

function blackoutClick() {
    closeSkyBox(function(){
    pev_for_country = '';
});
于 2013-08-28T17:00:12.043 回答
0

我相信另一种方法是将事件设置为空......

$(document).on('click', '#blackout', null);

在您在第二页上重新设置之前。

于 2013-08-28T17:03:29.900 回答