jQuery使用同一个类的多个按钮来返回一个值

Ste*_*Hat 17 javascript jquery

我有一个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>
Run Code Online (Sandbox Code Playgroud)

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

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

Ale*_* T. 14

试试这个

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


Pra*_*lan 6

只是this.id用来获取元素的id

$(".remove").click(function() {
  alert(this.id);
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)


小智 6

未来观众的香草选择.

  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);
        };
    }
})();
Run Code Online (Sandbox Code Playgroud)
<div>Some entry here
    <button id="0" class="remove">Remove</button>
</div>
<div>Another entry here
    <button id="1" class="remove">Remove</button>
</div>
Run Code Online (Sandbox Code Playgroud)