jquery on click ID only works for first output

后端 未结 2 609
耶瑟儿~
耶瑟儿~ 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条回答
  • 2021-01-26 12:00

    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
    });
    
    0 讨论(0)
  • 2021-01-26 12:09

    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");
        }
      });
    });
    
    0 讨论(0)
提交回复
热议问题