jquery on click ID only works for first output

倖福魔咒の 提交于 2019-12-02 10:24:41

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 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");
    }
  });
});

In HTML Ids must be unique. If you have multiple elements, you should use classes.

echo "<span class='delete_link' data-linkid='" . $link->id . "' class='glyphicon glyphicon-remove'></span>";

Script, Use class selector to bind event

$('.delete_link').click(function(){
   //Your code will work fine
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!