如何使用jquery隐藏/更新/显示具有相同ID的多个实例

how do i hide/update/show multiple instances with the same ID with jquery?

本文关键字:ID 实例 jquery 何使用 隐藏 更新 显示      更新时间:2023-09-26

我有一个jQuery脚本,有人可以在其中单击按钮将此项目添加到他们的收藏夹中。现在,问题是我想在页面上多次添加这个按钮——完全相同的按钮,具有相同的代码。当我点击其中一个按钮时,第一个按钮会更新,但其他按钮不会。有没有办法更新所有匹配的ID?换句话说,除了第一个案例外,对页面上所有匹配的案例运行此操作?

代码如下:

$(document).on('click','#add-to-list',function (e) {
               e.preventDefault();
               var id = $(this).data("id");
               $.ajax({
                 url: "http://xxx.xxx.xxx.xxx/add_to_list?id=" + id,
                 type: "GET",
                 dataType: 'json',
                 success: function(json) {
                     if(json.valid == 1) {
                         $("#list-button").hide();
                         $("#list-response").html('Added to Favorites');
                         $("#list-response").show();
                     }
                 },
                 timeout: 10000
               });
             });

然后在页面上,很明显我有多个实例

<div id="list-button">
 (button here)
</div>
<div id="list-response">
 (initially hidden)
</div>
jquery中的

id将只对单个按钮有效,class将对每个按钮有效,因此对于此操作,您必须使用class而不是id,请单击此链接--

什么';jQuery中class和id的区别是什么?

元素的ID必须是唯一的,ID选择器将只获取具有给定ID的第一个元素。

在您的情况下,您可以使用类而不是ID,然后使用遍历方法来针对适当的元素来显示/隐藏

$(document).on('click', '.add-to-list', function (e) {
    e.preventDefault();
    var $this = $(this);
    var id = $this.data("id");
    $.ajax({
        url: "http://xxx.xxx.xxx.xxx/add_to_list?id=" + id,
        type: "GET",
        dataType: 'json',
        success: function (json) {
            if (json.valid == 1) {
                $this.closest('.list-button').hide().next().html('Added to Favorites').show();
            }
        },
        timeout: 10000
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="list-button">(button here)</div>
<div class="list-response">(initially hidden)</div>