2012-05-29 87 views
1

對不起,如果標題不夠清晰,我有<a>元素具有相同的類,當用戶點擊每個單獨的jquery代碼應運行,問題是當單擊第一個元素,並在它完成運行整個代碼如果我點擊第二個元素,它留下第一個不完整,並在第二個元素上運行代碼,它應該同時工作(順便說一句,它應該發送數據到PHP文件,它工作正常,即使我點擊許多元素類不工作)jQuery each()如果第二個元素被點擊,每個()沒有繼續執行第一個元素的代碼?

下面的代碼:

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'); }); 
       } 
      }); 
     }); 
    }); 

所以我究竟做錯了什麼?

並提前致謝。

回答

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'); }); 
    } 
}); 
+0

我以前試過相同的代碼,它也不工作。 – Pierre

+0

您在控制檯中遇到什麼錯誤? –

+0

請注意,我在'$ this'聲明之前添加了'var',以確保它在'$ .post'回調中仍然有作用域。 –

1

你有$此變量,設置爲$(本)......哪裏是$這個定義?如果它超出了函數的範圍,那就是你的問題!

相關問題