jQuery:附加事件、调用事件

发布于 2024-09-24 06:24:00 字数 341 浏览 1 评论 0原文

在一段代码中,我有这样的:

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

在另一段代码中,我有这样的:

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

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

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

In one section of code I have this:

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

In another section of code, I have this:

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

The bind() is executed before the trigger(), but when I view the page, I never get an alert().

Why not? What am I doing wrong with events?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

腹黑女流氓 2024-10-01 06:24:01

也许当你执行时你的#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 示例

Perhaps your #searchbar is not part of the DOM when you execute:

  // 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");
});

This type of stuff often happens if .bind() is outside the document ready or because #searchbar is added dynamically.

To make sure onOptionsApplied is bound correctly even under these conditions, use .live() or .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

烟织青萝梦 2024-10-01 06:24:01

我也尝试过并且效果很好。

将绑定函数放入就绪处理程序中,然后触发事件...它应该会顺利进行

I also tried it and works fine.

put the bind function in the ready handler and then trigger the event ...it should go smooth

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文