关于点击ID的jQuery仅适用于第一个输出 [英] jquery on click ID only works for first output

查看:79
本文介绍了关于点击ID的jQuery仅适用于第一个输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于存在链接列表的仪表板,如果有人单击删除"按钮,我想执行一些操作.但是不知何故,它仅在第一个具有id ="delete_link"的链接上作出响应.我需要更改什么才能使所有lnik都可以使用此功能?

For a dashboard where there is a list of links I want to perform some actions if someone clicks the delete button. But somehow it only responds on the first link with id="delete_link". What do I need to change to let this work for all of the lniks?

Php代码:

if($count < 1) {
        echo "There are no links in this category yet";
    }

while($link = $query->fetch(PDO::FETCH_OBJ)) {
    echo "<li><a href='" . $link->url . "' TARGET='_BLANK'>" . $link->title . "</a>";
    if($_SESSION['role'] == '2') {
        echo "<span style='float:right;opacity:0.85;' class='glyphicon glyphicon-pencil'></span><span style='float:right;opacity:0.85;margin-right:10px;' id='delete_link' data-linkid='" . $link->id . "' class='glyphicon glyphicon-remove'></span>";
    }
    echo "</li>";
}
echo "</ul>
        </div>
            </div>";
}

jQuery:

$(document).ready(function(){

    $('#delete_link').click(function(){
        var dataId = $(this).data('linkid');
        var confirmDelete = confirm("Are you sure you want to delete this link?");
        if(confirmDelete == true) {
            alert(dataId);
            // $.ajax({
                // type: "POST",
                // url: "delete_link.php",
                // data: ""
            // })
        }else {
            alert("FALSE");
        }
    });
});

提前谢谢!

推荐答案

使用以下代码.将class'delete_link'分配给元素而不是id.

use below code . assign class 'delete_link' to elements instead of id.

    echo "<span style='float:right;opacity:0.85;' class='glyphicon glyphicon-pencil'></span><span style='float:right;opacity:0.85;margin-right:10px;' class='delete_link' data-linkid='" . $link->id . "' class='glyphicon glyphicon-remove'></span>";

id在DOM中必须唯一.因此事件仅适用于具有相同ID的i元素.

id must be unique in a DOM. so event only work on i element who have same id.

还需要检查事件委托,以将事件附加到动态创建的元素上.事件委托使我们可以将单个事件侦听器附加到父元素,该元素将为与选择器匹配的所有后代触发,无论这些后代现在存在还是将来添加.

also you need to check Event delegation to attach event to dynamically created element. Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

$(document).ready(function(){

  $(document).on('click','.delete_link',function(){
      var dataId = $(this).data('linkid');
      var confirmDelete = confirm("Are you sure you want to delete this link?");
    if(confirmDelete == true) {
        alert(dataId);
        // $.ajax({
            // type: "POST",
            // url: "delete_link.php",
            // data: ""
        // })
    }else {
        alert("FALSE");
    }
  });
});

这篇关于关于点击ID的jQuery仅适用于第一个输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆