很抱歉,如果标题不够清楚,当用户点击每个单独的jquery代码时,<a>
元素具有相同的类,问题是单击第一个元素时和之前它完成了运行整个代码,如果我点击第二个元素,它留下第一个不完整的并在第二个上运行代码,它应该同时工作(顺便说一下,它应该发送数据到一个PHP文件,它工作正常,即使我按类别点击很多元素不起作用)
这是代码:
jQuery(function($) {
$('.anchor-tag-class').each(function() {
$(this).click(function() {
$this = $(this);
var id = $this.attr('data-id');
if ( $this.hasClass('on') ) {
$this.removeClass('on');
$this.addClass('loading');
$.post("process.php", { element_id: id, status: 'off' }, function(data) { $this.addClass('off').removeClass('loading'); } );
} else {
$this.removeClass('off');
$this.addClass('loading');
$.post("process.php", { element_id: id, status: 'on' }, function(data) { $this.addClass('on').removeClass('loading'); } );
}
});
});
});
所以我做错了什么?
并提前致谢。
答案 0 :(得分:2)
在这种情况下,您不需要each()
,因为代码只会针对引发事件的特定元素运行。您还可以将函数链接到$this
变量。
试试这个:
$('.anchor-tag-class').click(function() {
var $this = $(this);
var id = $this.attr('data-id');
if ( $this.hasClass('on') ) {
$this.removeClass('on').addClass('loading');
$.post("process.php", { element_id: id, status: 'off' }, function(data) { $this.addClass('off').removeClass('loading'); } );
}
else {
$this.removeClass('off').addClass('loading');
$.post("process.php", { element_id: id, status: 'on' }, function(data) { $this.addClass('on').removeClass('loading'); } );
}
});
答案 1 :(得分:1)
你有一个$ this变量,设置为$(this)...这个$定义在哪里?如果它不在函数范围内,那就是你的问题!