【问题标题】:JQuery replacement of live :: `delegate` or `on`JQuery 替换 live :: `delegate` 或 `on`
【发布时间】:2013-06-19 13:15:05
【问题描述】:

根据 jQuery API 描述:live 在最新版本中被完全移除。但它在我们的项目中被广泛使用。例如:

$('div.collapsed').live('mouseover', function () {
        TBD.GENERAL.showLoginOther(this);

});

$(".info_bar .filter a, .pagination a").live("click", function () {
    TBD.DHTML.shadeWithLoading($(this).data('container-id'));
    $.getScript(this.href);
    return false;
});

$("form[loading-effect]").live('ajax:before', function () {
    $(this).find('.button_panels, .loading_panels').toggle();
});

.........

等等

现在,如果我想使用最新的 jquery,什么是 live 的正确替换?委托还是上?

期待一点解释。在此先感谢

【问题讨论】:

  • 你可以在我认为的文档中找到最好的解释
  • 最简单的解决方案是不要更新您的 jQuery 版本,除非您有其他特定原因。
  • 我已经决定升级了:)

标签: jquery jquery-on jquery-delegate


【解决方案1】:

由于 .live() 已被弃用,您最好使用 .on() 喜欢

$('div.collapsed').on('mouseover', function () {

或者可以使用like

$(document).on('mouseover','div.collapsed', function () {

因为

  1. 您不能将 .live() 用于可重复使用的小部件。
  2. stopPropagation() 不适用于 live。
  3. live() 比较慢。
  4. live() 不可链接。

并且 .on() 方法提供了附加事件处理程序所需的所有功能。

【讨论】:

  • 为什么不delegate?或者为什么on。解释将不胜感激
  • 它们都不等同于 live()。 Live 将事件处理程序附加到文档级别:$(document).on('mouseover','div.collapsed', function () {...})
  • 两者都和你说的我想的一样
  • 你的编辑现在更好了 ;) +1 但你应该删除 $('div.collapsed').on('mouseover', function () {...}) 这会带来混乱不委托事件,在这里,它相当于 .bind()
猜你喜欢
  • 1970-01-01
  • 2014-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 2013-05-03
  • 2011-12-14
相关资源
最近更新 更多