开发者

How do I tell which Anchor was clicked using JQuery?

I have a div with two links:

<div id="copyrightFooter">
    <p>Copyright &copy; 2011 MY Company, LLC. All rights reserved. please review our 
        <a  id="privacyPolicy" style="color: #9DB2E7;font-weight:bold" href="#">Privacy Policy</a> and our <a id="terms" styl开发者_运维知识库e="color: #9DB2E7;font-weight:bold" href="#">Terms of Use</a>
    </p>
</div> <!-- copyrightFooter-->

I am currently capturing the clicks on those two links with JQuery:

jQuery(function ($) {
    // Load dialog on page load

    // Load dialog on click
    $('#copyrightFooter a ').click(function (e) {
        $('#basic-modal-content').modal();
        return false;
    });

});

problem is, this code works for BOTH links. I'd like to "switch/case" which ID i've clicked on so that I can modal-dialog a different DIV. Nothing I do works? "alerting" the ID brings back "undefined" or something similar, so switch case doesn't work. What am I doing wrong?


$('#copyrightFooter a ').click(function (e) {
    alert($(this).attr('id'));
});

Should work fine.


Using this in the event handler function will give you a reference to the clicked element. For example, to get the id of the clicked element you can do:

$('#copyrightFooter a ').click(function (e) {
    var clickedID = this.id;
});

You could also use jQuery's $(this).attr("id");, but there's no need to overuse jQuery when a simple pure JavaScript statement will suffice.


jQuery(function ($) {
    // Load dialog on page load

    // Load dialog on click
    $('#copyrightFooter a ').click(function (e) {
        if($(this).attr("id") == "privacyPolicy")
        {
            alert("display Modal 1");
        }else  if($(this).attr("id") == "terms"){
          alert("display Modal 2");
        }

        return false;
    });

});

Use $(this).attr("id"); to get the id of div you clicked.

Here is a working example: http://jsfiddle.net/HPsgE/


You could do:

$('#copyrightFooter a ').click(function (e) {
    var id = $(this).attr("id");
    switch(id){
        case "privacyPolicy": 
            ... 
           break;  
        case "terms": 
           ... 
           break;
    }        
    return false;
});

Hope this helps. Cheers


$('#copyrightFooter a').click(function (e) {

    switch($(this).attr('id')){
        case 'privacyPolicy': id = '#basic-modal-content'; break;
        case 'terms': id = '#basic-modal-content'; break;
    }

    $(id).modal();
    return false;

});


You can check the id like this:

$('#copyrightFooter a ').click(function (e) {
    if(this.id=="privacyPolicy"){
        ..
    }
    else{
        ..
    }
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜