2015-11-05 260 views
1

我有一個簡單的頁面,有四張卡片(Div),每個卡片都有一個按鈕。我寫了一些jQuery的希望,當我點擊按鈕,我可以更改類的按鈕文本& ...並切換兩種狀態,我繼續點擊它們。點擊jquery更改按鈕

我的下面的代碼似乎適用於第一個按鈕完美...但沒有任何其他人。

<!DOCTYPE html> 
<html> 

<head> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> 

    <script> 
     $(document).ready(function() { 

      $("#un_btn").click(function() { 
       if ($(this).attr('class') == 'btn_s') { 
        $(this).html('Undo?'); 
        $(this).removeClass('btn_s'); 
        $(this).addClass('notsu'); 
       } else { 
        $(this).html('Mark as not suitable?'); 
        $(this).removeClass('notsu'); 
        $(this).addClass('btn_s'); 
       } 
      }); 
     }); 
    </script> 

</head> 

<body> 
    <div class="card"> 
     <p>Card 1</p> 
     <button class="btn_s" id="un_btn">Mark as not suitable?</button> 
    </div> 

    <div class="card"> 
     <p>Card 2</p> 
     <button class="btn_s" id="un_btn">Mark as not suitable?</button> 
    </div> 

    <div class="card"> 
     <p>Card 3</p> 
     <button class="btn_s" id="un_btn">Mark as not suitable?</button> 
    </div> 

    <div class="card"> 
     <p>Card 4</p> 
     <button class="btn_s" id="un_btn">Mark as not suitable?</button> 
    </div> 

</body> 

</html> 

我在做什麼錯?我怎樣才能得到開關在每個相應的div(卡)內的每個按鈕上工作?

回答

1
  1. ID應該是唯一的用類代替相似的元素。
  2. 使用hasClass來檢查元素是否有一些類,而不是使用attr('class')
  3. 方法addClass,相同的元素removeClasshtml可以鏈接。
  4. 代替使用addClassremoveClass,toggleClass可以與兩個類一起使用。

Demo

$(document).ready(function() { 
 

 
    // Bind click event on all the buttons inside .card 
 
    $(".card button").click(function() { 
 
    
 
    // Check if the clicked button has class `btn_s` 
 
    if ($(this).hasClass('btn_s')) { 
 
     $(this).html('Undo?').toggleClass('btn_s notsu'); 
 
    } else { 
 
     $(this).html('Mark as not suitable?').toggleClass('notsu btn_s'); 
 
    } 
 
    }); 
 
});
.notsu { 
 
    color: red; 
 
} 
 
.btn_s { 
 
    color: green; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="card"> 
 
    <p>Card 1</p> 
 
    <button class="btn_s">Mark as not suitable?</button> 
 
</div> 
 

 
<div class="card"> 
 
    <p>Card 2</p> 
 
    <button class="btn_s">Mark as not suitable?</button> 
 
</div> 
 

 
<div class="card"> 
 
    <p>Card 3</p> 
 
    <button class="btn_s">Mark as not suitable?</button> 
 
</div> 
 

 
<div class="card"> 
 
    <p>Card 4</p> 
 
    <button class="btn_s">Mark as not suitable?</button> 
 
</div>

0

你檢查的ID名稱,而不是在你的jQuery類。你真的不應該有同樣的Id,因爲它會導致這樣的問題。

如果更改行:

$("#un_btn").click(function(){ 

$(".btn_s").click(function(){ 

這工作得很好。

Here是它的這種變化

0

點擊工作正常渲染單元工作一的jsfiddle。由於您要動態添加元素,因此您必須使用on。 它看起來像你動態地添加這個元素,所以你需要使用委派事件偵聽器:

修改代碼

$("#un_btn").click(function() {}); to 

$(document).on('click', "your selector", function() { }); 

選擇可能是class和id。 .btn_s或#un_btn