jquery on click ID only works for first output

后端 未结 2 629
耶瑟儿~
耶瑟儿~ 2021-01-26 11:43

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=\"delet

2条回答
  •  Happy的楠姐
    2021-01-26 12:09

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

        echo "";
    

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

提交回复
热议问题