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 code:
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");
}
});
});
Thanks in advance!
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
});
来源:https://stackoverflow.com/questions/29253221/jquery-on-click-id-only-works-for-first-output