2015-02-07 55 views
0

我有一個對話框,從ajax調用中獲得學生列表,我用jQuery的.html()方法加載數據。檢查一個元素被點擊不工作jquery

我把這樣的html數據放到對話框中。我想讓每個學生的名字都是可點擊的。當我點擊第一個時,所選.student_list_div的背景應該是​​。如果我再次點擊,我應該使它background none。如果再次點擊,顏色應該是綠色的,以使用戶知道它被選中或不。我也做了jquery方法,但它不能正常工作。

<a href='' class='student_list' id='studentid1'><div class="student_list_div"> 
StudentName1</div></a> 
<a href='' class='student_list' id='studentid2'><div class="student_list_div"> 
StudentName2</div></a> 
and so on....... 

我的jquery方法是這樣的。

$("#dialog_wrapper").on('click','.student_list',function(){ 
      if($(this).data('clicked')) 
      { 
       $(this).find('.student_list_div').css('background-color','none'); 
      } 
      else 
      { 
       $(this).click(function(){ 
        $(this).data('clicked',true); 
        $(this).find('.student_list_div').css('background-color','green'); 
       }); 
      } 


      return false; 
     }); 

請幫我

+0

你可以發佈jsfiddle嗎? – 2015-02-07 15:43:03

+0

你爲什麼要綁定另一個點擊事件處理程序。刪除'$(this).click(function(){' – Satpal 2015-02-07 15:45:27

回答

1

你並不需要你的第一個點擊事件中綁定額外的點擊事件處理處理程序。此外,我認爲如果它是真實的,你不會將clicked屬性更改爲false。

$("#dialog_wrapper").on('click', '.student_list', function() { 
 
    if ($(this).data('clicked')) { 
 
    $(this).find('.student_list_div').css('background-color', 'none'); 
 
    $(this).data('clicked', false); 
 
    } else { 
 
    $(this).data('clicked', true); 
 
    $(this).find('.student_list_div').css('background-color', 'green'); 
 
    } 
 

 

 
    return false; 
 
});

而且你可以通過具有「.clicked」類和使用jQuery的toggleClass到點擊時切換它達到同樣的效果。

$("#dialog_wrapper").on('click', '.student_list', function() { 
 
    $(this).find('.student_list_div').toggleClass('.clicked') 
 
});
.clicked { 
 
    background-color: green; 
 
}

+0

你的運行代碼片段沒有顯示任何東西 – Techy 2015-02-07 15:54:53

+0

第二個版本(切換一個類)絕對是一個更好的選擇。請注意,原始HTML也是無效的(div是一個* block *元素,因此在一個* inline *元素的錨點內無效) – 2015-02-07 15:59:56

1

除此之外的任何其他問題,直列元素,就像一個錨,不能包含元素(如一個div)。

改爲使用<span> s作爲內部元素。

+0

我已經使用了跨度,但是一旦它被選中,背景顏色也不會再去。 – Techy 2015-02-07 15:53:00

+0

您也在點擊處理程序中連接點擊處理程序 - 從來不是一個好主意。 – 2015-02-07 15:56:52

+0

我明白了我的錯誤。謝謝讓我意識到。我也提出了你的答案 – Techy 2015-02-07 15:57:48

1

您正在綁定單擊處理程序中的單擊事件處理程序。刪除$(this).click(function(){

使用

$("#dialog_wrapper").on('click', '.student_list', function() { 
    if ($(this).data('clicked')) { 
     $(this).find('.student_list_div').css('background-color', ''); 
    } else { 
     $(this).data('clicked', true); 
     $(this).find('.student_list_div').css('background-color', 'green'); 
    } 
    return false; 
}); 

重要:錨一個不能包含div,使用span代替

+0

這是第一次工作。即如果它不是錨點標籤沒有點擊,它會使第一次點擊時背景綠色。如果我點擊再次,背景顏色不會刪除 – Techy 2015-02-07 15:50:33

+0

@Techy,嘗試與'.css('background-color','')' – Satpal 2015-02-07 15:54:16

+0

這也不工作。當我添加$(this)。數據('點擊',錯誤);在第一個條件內工作,感謝您的幫助。 – Techy 2015-02-07 15:56:52