jQuery使用同一类的多个按钮返回一个值[重复]

Posted

技术标签:

【中文标题】jQuery使用同一类的多个按钮返回一个值[重复]【英文标题】:jQuery using multiple buttons of the same class to return a value [duplicate] 【发布时间】: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 调用?

【问题讨论】:

【参考方案1】:

试试这个

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

【讨论】:

【参考方案2】:

未来观众的香草选项。

    选择类remove的所有元素 遍历元素,分配点击处理程序 点击删除父元素 将 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');
);

【讨论】:

以上是关于jQuery使用同一类的多个按钮返回一个值[重复]的主要内容,如果未能解决你的问题,请参考以下文章

Bootstrap 4如何在同一页面上使用多个jQuery版本[重复]

防止重复发送Ajax请求的解决方案

如何使用PHPUnit测试一个方法调用了同一个类的其他方法,但是没有返回值

jQuery选择具有多个类的输入[重复]

具有相同ID的jQuery多个按钮[重复]

同一页面上的多个版本的 JQuery [重复]