开发者

jQuery get id of dynamic id link

I'm new to jquery and have looked around all day but can't resolve what's a very simple idea :)

Here's the test code:

js:

$(document).ready(function(){
    $('#transgenic_div').click(function(){
        var selected_transgenic_id = $(this).attr("id");
        alert(selected_transgenic_id);          
    });

});

html:

<div id="transgenic_div">
<p><a class="transgenic_button" id="56">item number 5开发者_JAVA技巧6</a></p>
<p><a class="transgenic_button" id="57">item number 57</a></p> etc
</div>

This just gives the alert "tansgenic_div" I'm trying to pass the selected id to another function - but for now just testing with the alert...


Try getting the ID from the target/source element of the click event:

$('#transgenic_div').click(function(e){
    var selected_transgenic_id = $(e.target).attr("id"); // or e.target.id
    alert(selected_transgenic_id);          
});

Also, IDs should not start with numbers in HTML4, I would suggest applying a prefix.

If you want to match only anchors using this technique, you can do so like this:

$('#transgenic_div').click(function(e){
    var t = e.target;
    if(t.tagName.toLowerCase() === "a") {
        var selected_transgenic_id = $(t).attr("id"); // or t.id
        alert(selected_transgenic_id);   
    }       
});


If I understood your question, you don't really want to match the main <div> but the inner links:

$(document).ready(function(){
    $('#transgenic_div p a').click(function(){
        var selected_transgenic_id = $(this).attr("id");
        // Or simply: this.id
        alert(selected_transgenic_id);          
    });
});

(BTW, valid IDs cannot start with a digit unless you are using HTML 5.)

Full working example:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript"><!--
$(document).ready(function(){
    $('#transgenic_div p a').click(function(){
        alert(this.id);
    });
});//--></script>
</head>
<body>

<div id="transgenic_div">
<p><a class="transgenic_button" id="56">item number 56</a></p>
<p><a class="transgenic_button" id="57">item number 57</a></p> etc
</div>

</body>
</html>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜