【问题标题】:jQuery using multiple buttons of the same class to return a value [duplicate]jQuery使用同一类的多个按钮返回一个值[重复]
【发布时间】:2015-08-04 00:38:00
【问题描述】:

我有一个由 PHP 生成的条目列表,每个条目都在自己的 div 中,并且每个条目都有一个唯一的 ID。我正在尝试开发一个 AJAX 调用,它可以根据 ID 删除每个条目,但是每当我运行下面的脚本时,它总是返回 0。

<div>
    Some entry here
    <button id="0" class="remove">Remove</button>
</div>
<div>
    Another entry here
    <button id="1" class="remove">Remove</button>
</div>
// ... and so on

<script>
    $(".remove").click(function() {
        var id = $(".remove").attr('id');
        alert(id); // debug
        // AJAX call here
    });
</script>

以前我尝试过同样的事情,除了相反的方法 - PHP 返回的 id 在 class 属性中,id 属性的值是 'remove' ,这只为第一个按钮返回 0。第二个按钮根本没有调用 jQuery 脚本。

如何将唯一 ID 传递给同一个 jQuery 调用?

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    试试这个

    $(".remove").click(function() {
        var id = $(this).attr('id'); // $(this) refers to button that was clicked
        alert(id);
    });
    

    【讨论】:

      【解决方案2】:

      未来观众的香草选项。

      1. 选择类remove的所有元素
      2. 遍历元素,分配点击处理程序
      3. 点击删除父元素
      4. 将 id 记录到控制台

      (function () {
          "use strict";
          var buttons = document.getElementsByClassName('remove');
          for ( var i in Object.keys( buttons ) ) {
              buttons[i].onclick = function() {
                  this.parentElement.remove();
                  console.log(this.id);
              };
          }
      })();
      <div>Some entry here
          <button id="0" class="remove">Remove</button>
      </div>
      <div>Another entry here
          <button id="1" class="remove">Remove</button>
      </div>

      【讨论】:

        【解决方案3】:

        只需使用 this.id 即可获取元素的 id

        $(".remove").click(function() {
          alert(this.id);
        });
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <div>
          Some entry here
          <button id="0" class="remove">Remove</button>
        </div>
        <div>
          Another entry here
          <button id="1" class="remove">Remove</button>
        </div>

        【讨论】:

          【解决方案4】:
          $(".remove").on("click",function() {
              var id = $(this).attr('id');
              console.log(id);
          });
          

          【讨论】:

            【解决方案5】:

            你需要使用this关键字来引用被点击的元素:

            $('.remove').click(function() {
                var id = this.id;
                // OR
                var id = $(this).attr('id');
            });
            

            【讨论】:

              猜你喜欢
              • 2013-12-18
              • 1970-01-01
              • 2013-08-30
              • 1970-01-01
              • 2013-10-25
              • 1970-01-01
              • 1970-01-01
              • 2018-12-19
              • 1970-01-01
              相关资源
              最近更新 更多