开发者

How to check class of a clicked link

I have several links on my page and want to run a JQuery Script when a user clicked on it. Previou开发者_运维百科sly 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:

<a data-user="1" class="mylink">

Your click handler could then look like this:

$('a').click(function(){
    var userId = $(this).data('user');
});

This works because data imports data-* attributes.

If there is no data-user attribute set, userId will be undefined.


this.className or if you want to do it using a jQuery object (there is no good reason to do so): $(this).attr('className')

From this string you could extract the ID with a regex (/userid_([0-9]+)/)...


However, using the HTML5 data- attributes would be better. Since browsers are very tolerant about unknown attributes they do not break anything and will work fine with HTML4 and XHTML:

<a class="mylink" data-userid="1">---</a>
...
var userid = $(this).data('userid');

The nice thing is: if you put valid JSON in a data attribute, .data('yourAttr') will automatically return an object instead of a string.


Try this

http://jsfiddle.net/Wa6gN/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜