2015-11-05 266 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