Jquery 单击更改按钮

Jquery change button on click

我有一个简单的页面,其中有四张卡片 (Divs),每张卡片都有一个按钮。我写了一些 jquery,希望当我点击按钮时,我可以更改按钮的 class 和文本...并在我继续点击它们时在两种状态之间切换。

我的以下代码似乎对第一个按钮非常有效...但对其他任何按钮都无效。

<!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. ID 应该是唯一的 使用 class 代替相似的元素。
  2. 使用 hasClass 检查元素是否有一些 class 而不是使用 attr('class')
  3. 可以链接同一元素上的方法 addClassremoveClasshtml
  4. 而不是使用 addClassremoveClasstoggleClass 可以与两个 class 一起使用。

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>

您正在检查您的 jquery 中的 ID 名称而不是 Class。你真的不应该让 Id 相同,因为它会导致这样的问题。

如果换行:

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

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

这很好用。

Here 是它的一个 JsFiddle 用于此更改

点击对呈现的元素效果很好。由于您正在动态添加元素,因此您必须为此使用 on 。 看起来您正在动态添加此元素,因此您需要使用委托事件侦听器:

修改你的代码

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

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

选择器可以是 class 或 Id。 .btn_s 或 #un_btn