Suppose I generate a list of records on my web page via PHP, and suppose each has a link beside 开发者_如何学编程it. And let's say that a modal window pops up when I click the link, and an edit form then shows in the modal.
I could easily make this happen like this:
<a href="javascript:showEditModal(12345)">Edit</a>
But I'd prefer to use a jQuery event listener:
<a class="edit" href="#">edit</a>
$('.edit').click(function(event) {
showEditModal(recordId);
});
As you can see, using an event listener, I do not have a way of knowing which record the user wants to edit via the modal.
How can I allow the user to specify which record to edit while still using an event listener for the edit links?
If using jQuery >= 1.4.3, you can specify a "data-id" attribute (HTML5! woohoo) on the link and grab it using jQuery's data() method:
<script>
$(function() {
$('a.edit').click(function() {
alert( $(this).data('id') );
});
});
</script>
<a href="#" class="edit" data-id="12345">edit</a>
And here's a demo on jsFiddle.
Put the ID in an attribute of the element.
<a class="edit" href="#12345">edit</a>
$('.edit').click(function(e) {
e.preventDefault();
recordId = $(this).attr("href").substr(1);
showEditModal(recordId);
return false;
});
精彩评论