【问题标题】:jQuery event bubbling with AJAX使用 AJAX 冒泡的 jQuery 事件
【发布时间】:2012-05-31 08:33:44
【问题描述】:

我很难让一些 jQuery 函数正常工作。

我的网站上有一个点赞按钮,该按钮在添加新项目之前一直有效,然后停止工作。 当我有以下代码时,这有效:

$('.like').toggle(
    function() {
        console.log('href');
    }, function() {
        console.log('rel');
    }
);

我的一个朋友指导我使用事件冒泡,但我很难让它发挥作用。

这是我目前拥有的。

简单的 HTML

​<button href='123.html' rel='456.html' class='like'>Click here</button>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

jQuery,包裹在 $(document).ready( ... 我尝试了切换功能,似乎按钮在第一次单击时处于休眠状态,然后突然唤醒并执行事件。

$('body').click(function(event) {
    if ($(event.target).is('.like')) {
        var $like = $(event.target);
        $like.toggle(
            function() {
                console.log('href');
            }, function() {
                console.log('rel');
            }
        );
    }
});​

代码应该是什么样子才能在添加新项目时继续工作并确保按钮不会以这种方式运行

这是一个小提琴。

http://jsfiddle.net/_entreprenerd/SpmbQ/

【问题讨论】:

  • 你能发布一个小提琴来重现这个问题(或一个简单的演示页面)吗?
  • @F.Calderan 刚刚在描述中添加了小提琴。谢谢
  • 为什么在之前没有问题的情况下要进行事件冒泡?
  • @RakeshJuyal 如果您阅读了前面的内容,在添加新的 ajax 项目之前它工作正常,然后“喜欢”按钮停止工作。

标签: javascript ajax dom jquery


【解决方案1】:

您需要委托事件处理程序来解决您的问题。

$('body').on('click', '.like', function() {
  $(this).toggle(
    function() {
        console.log('href');
    }, function() {
        console.log('rel');
    });
}).click();

.on()

你还有delegate()

$('body').delegate('.like', 'click', function() {
  $(this).toggle(
    function() {
        console.log('href');
    }, function() {
        console.log('rel');
    });
}).click();

注意您可以使用 container 来代替 body,其中包含 .like

【讨论】:

  • 感谢您的详细解释,但我仍然发现它做同样的事情。看到这个小提琴。 jsfiddle.net/_entreprenerd/SpmbQ
  • like 按钮在 href 和 rel 中包含一个like/like,用于触发一个like 或unlike。我也尝试了chrome和firefox中的jsfiddle,仍然需要一键唤醒,然后功能才开始工作......
  • 这个答案的代码需要额外的点击,因为在点击事件中它只是使用切换功能注册一个新的点击事件。问题是切换不是一个事件,所以它不能被委托,所以你需要自己“模拟”切换行为。检查我的答案。
【解决方案2】:

问题是,我们不能委托“toggle”,因为toggle 不是一个事件,它只是jQuery 中的一个方法。因此,您需要为委托事件实现自己的切换功能。

示例解决方案:

$("body").on("click", ".like", function () {
    var $this = $(this);
    var toggled= $this.data("toggled");
    if (toggled) {
        console.log('rel');
    } else {
        console.log('href');
    }
    $this.data("toggled", !toggled);
});

我还建议将上述代码中的选择器从“body”更改为 .like 元素的父容器,因此委托在文档树上的路径更短。

还有一个小提琴样本:http://jsfiddle.net/t2pXr/3/

【讨论】:

  • 你的传奇!谢谢,我将使用新的附加 ajax 项目对其进行测试,看看它是否有效。
【解决方案3】:

您可能正在寻找 .on()(或 .delegate() 用于 jQuery 版本

【讨论】:

    【解决方案4】:

    代码悖论的解决方案或 在 ajax 调用在 DOM 中添加新元素后挂钩事件。但是codeparadox的解决方案更好。

    【讨论】:

      猜你喜欢
      • 2011-10-20
      • 1970-01-01
      • 2011-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-11
      • 2015-04-16
      • 1970-01-01
      相关资源
      最近更新 更多