开发者

How to differentiate onclick fun on multiple anchor tags with id in JQuery

Could you please suggest me how to handle multiple anchor tags for click functionality?

My code is like :

<a id="test1" href="#" >test1</a>
<a id="test2" href="#" >test2</a>

My jQuery functionality is :

$('a').click(function(event) {
    alert('click');
});

The jQuery click functionality wo开发者_Go百科rks for all anchor tags, but I want to differentiate the jQuery functionality based on id attribute ..


Look at the id on this and make an if statement or a switch (switch is recommended):

$('a').click(function(event) {
    switch(this.id) {
        case 'test1':
            alert('link with an id of test1!');
            event.preventDefault();
            break;
        case 'test2':
            alert('link with an id of test2!');
            event.preventDefault();
            break;
        default:
            //Default behavior
    }
});


You want to do something different depending on the ID?

You could do something like

$('a').click(function(e){
    var id = $(this).attr('id');
    // switch depending on id
});

OR

$('#test1').click(function(e){ alert("you clicked test1"); });
$('#test2').click(function(e){ alert("you clicked test2"); });

But this wouldn't be very nice if you are then going to add multiple's to do the same thing.


You can get the id attribute.

$('a').click(function(event) {
    alert($(this).attr('id')+' clicked!');
});


you can read the id of the element and depending on the id make your functions

$('a').click(function(event) {
    if ($(this).attr("id") == 'test1')
    {
        alert('Test 1 was clicked');
    }
    else if ($(this).attr("id") == 'test2')
    {
        alert('Test 2 was clicked');
    }
});


If you want to bind to an element based on id:

$('#test1').click(function(event) {
   alert('test1 clicked');
});


This is my approach

$('a').click(
    function()
    {
        switch($(this).attr('id'))
        {
            case 'test1':
                // Do some work
                break;
            case 'test2':
                // Do some work
                break;
        }
    }
);


You can look at the id as suggested in the other answers but you can also attach data attributes on each tag with a custom data attribute (html5) or use the href, that can later be accessed from the onclick event (html5).

sample:

<a id="test1" data-my-custom-data="Insert" data-row-id="24" href="#" >test1</a>
<a id="test2" href="Insert" >test2</a>

$("a").click(function(event)
{
    alert($(this).attr("data-my-custom-data"));
    alert($(this).attr("data-row-id"));
    alert($(this).attr("href"));

    event.preventDefault(); // To avoid browsing to href...
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜