开发者

A way to pass variables (record ids) to jQuery event listeners?

开发者 https://www.devze.com 2023-01-31 16:45 出处:网络
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

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

精彩评论

暂无评论...
验证码 换一张
取 消