jQuery event bubbling with AJAX
jQuery event bubbling with AJAX
我很难让一些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/
您需要委托事件处理程序来解决问题。
$('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();
注意 您可以使用容纳.like
的容器代替主体。
问题是,我们不能委托"切换",因为切换不是一个事件,它只是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);
});
我还建议将上述代码中的选择器从 .like 元素的"body"更改为父容器,以便委托在文档树中的位置更短。
和一个示例小提琴:http://jsfiddle.net/t2pXr/3/
您可能正在寻找 .on()(或 .delegate() 用于 jQuery 版本 <1.7)
要么是代码悖论的解决方案,要么是在 ajax 调用在 DOM 中添加新元素后挂钩事件。但是代码悖论的解决方案更好。
相关文章:
- Ajax and Json with Rails
- Wordpress AJAX with raw javascript? NO Jquery
- KnockOut ajax with MVC
- Cross domain ajax with jsonP and codeigniter
- Ajax with node.js
- JSON and AJAX with Python
- jQuery Ajax with async: false 并返回数据
- Jquery ajax with google app engine post method
- jQuery AJAX with an interval
- jQuery ajax with ES6 Promises
- JQuery Ajax with Symfony
- Run jquery ajax with multi diemnstion array without form
- Wordpress ajax with async false
- Using Jquery Ajax with PHP
- jQuery Ajax with JSON
- Using jQuery (ajax) with TypeScript
- AJAX with Django
- AJAX with javascript vs. Php Form
- Zend AJAX with pure JavaScript
- jquery select2 (4.0) ajax with templateResult and templateSe