Passing parameter to jQuery function?

It looks very simple, but I have little experience with jQuery, and I cannot wrap it around.

Say I have a dynamically generated HTML table and there is a link in each row of this table:

<a id='edit'>Edit User</a> 

Now the link should call a function with each user ID as a parameter. I could do this inline liek:

 <a id='edit' onClick='editUser(<?php echo $row['id']; ?>)'>Edit User</a> 

But how to do it in jQuery?

I can call the function as follows:

 $('a#edit').click(function () { editUser() return false; }); 

But how to pass the identifier of this function? I know that I can first insert it into a hidden field and then get it from there using the id of the element, but of course, the best way?

I understand that all links have the same identifier in this way, so should I dynamically create link identifiers by adding user id? But what can I call jQuery?

+4
source share
3 answers

ids must be unique throughout HTML. So you can use the class selector and the data5 * HTML5 attribute:

 <a class="edit" data-id="<?php echo $row['id']; ?>">Edit User</a> 

and then:

 $('a.edit').click(function () { var id = $(this).data('id'); // do something with the id return false; }); 
+8
source

Use data-* attributes to pass parameters.

 <a class='edit' data-id='<?php echo $row['id']; ?>'>Edit User</a> $('a.edit').click(function () { editUser($(this).data("id")); return false; }); 
+2
source

As Kurt noted, data-id is the way to go if you use HTML5. If you are using HTML4, I would pass this in the link ID:

<a id='edit-321' class='edit'>Edit User</a>

Then you can do this (and use event.preventDefault() and not return false !):

 $('a.edit').click(function (evt) { editUser($(this).attr("id").substring(5)); evt.preventDefault(); }); 
0
source

Source: https://habr.com/ru/post/1411736/


All Articles