I have this PHP code in a loop for every post on the admin page of a blog:
echo '<a class="delete_link" id="delete_link_'.$row['rowid'].'">Delete</a>';
So it outputs:
<a class="delete_link" id="delete_link_1">Delete</a>
<a class="delete_link" id="delete_link_2">Delete</a>
<a class="delete_link" id="delete_link_3">Delete</a>
and so on…
By clicking on these links, I would like the browser to send a DELETE request through XHR, but I don't know how to set up the events an unobtrusive way. My example doesn't work, as sendDeleteRequest()
is fired with the last added id, no matter which link I click on:
function sendDeleteRequest(id) {
// I only put a simple alert in this function for now.
alert("Id of firing element: " + id);
}
onload = function() {
var deleteLinks = document.getElementsByClassName("delete_link");
for (var node in deleteLinks) {
deleteLinks[node].onclick = function() {
sendDeleteRequest(deleteLinks[node].getAttribute("id"));
}
}
}
What's wrong with this code? Anything else I should pay attention to? I've tried the same with addEventListener()
with no success. I still use XHTML 1.0 and I can't use jQuery in this project.
You could use something like this:
var deleteLinks = document.getElementsByClassName("delete_link");
for (var i = 0; i < deleteLinks.length; i++) {
deleteLinks[i].onclick = function() {
sendDeleteRequest(this.id);
}
}
Note, it's not wise to iterate an array with for (node in deleteLinks)
because that will include enumerable properties in the iteration in addition to the array elements. That type of iteration should only be used for iterating all properties of an object.
The main change I made in your code was to use a reference to this
to get the clicked on id
value. Your way of doing it caused problems because the for
loop and the value of node
had already run to completion when the click happened sometime later so the value of node
was not what you wanted it to be.