I have several links on my page and want to run a JQuery Script when a user clicked on it. Previously I’ve added a unique ID to the link, e.g.
<a id="user_1" class="mylink">
On my click event i then extracted the ID and started the processing on it
userid = $(this).attr('id').split('_')[1];
Now I have the problem that my page might have several links with the same id, and of course that’s not possible (afaik). So I think I have to add it as class, right? e.g.
<a class="mylink user_1">
Is this the best way? And how could I then extract the userID (‘1’) from the class? The jQuery-Script should of course also take care that there are some a-links without class ‘user_,,,’.
Many thanks in advance!
The nicest way of doing this is with custom
data-*attributes. These comply to the HTML5 standard and work universally in browsers older than that standard.So your link might look like this:
Your click handler could then look like this:
This works because
dataimportsdata-*attributes.If there is no
data-userattribute set,userIdwill beundefined.