jQuery:附加事件,调用事件

时间:2010-09-20 02:55:33

标签: javascript jquery triggers bind

在代码的一部分中我有:

$("#searchbar").trigger("onOptionsApplied");

在代码的另一部分,我有这个:

$("#searchbar").bind("onOptionsApplied", function () {
    alert("fdafds");
});

bind()trigger()之前执行,但是当我查看该页面时,我从未得到alert()

为什么不呢?我对事件做错了什么?

2 个答案:

答案 0 :(得分:1)

执行时,也许您的#searchbar不是DOM的一部分:

  // This will not work if #searchbar is not part of the DOM
  //   or if the DOM is not ready yet.
$("#searchbar").bind("onOptionsApplied", function () {
    alert("fdafds");
});

如果 .bind() 在文档之外或者动态添加#searchbar,则通常会发生此类问题。

要确保onOptionsApplied即使在这些条件下也能正确绑定,请使用 .live() .delegate()

// This can be outside document ready.
//   It binds all now and future #searchbars
$("#searchbar").live("onOptionsApplied", function () {
    alert("fdafds");
});

// Document ready
$(function() {
    // Whatever you do....

    // Make sure #searchbar is now part of the DOM

      // Trigger onOptionsApplied
    $("#searchbar").trigger("onOptionsApplied");
    });
});

jsFiddle example

答案 1 :(得分:0)

我也尝试过并且工作正常。

将bind函数放在ready处理程序中然后触发事件......它应该顺利