开发者

jquery problem identify appended anchor

开发者 https://www.devze.com 2023-01-19 13:45 出处:网络
I\'ve a problem to get the id of dynamically loaded anchor appended to a div.Here is the code that I get after filling the div:

I've a problem to get the id of dynamically loaded anchor appended to a div. Here is the code that I get after filling the div:

<di开发者_如何学Cv id="sotto_eti">
    <a href="#" id="a">a</a> <a href="#" id="b">b</a> <a href="#" id="c">c</a>
</div>

and here is the script:

<script>
$("#sotto_eti a").click(function()
{
    alert($(this).attr("id"));
});
</script>

Thanks in advance for your help

ciao h.


You can use .live() to handle dynamically loaded elements:

$("#sotto_eti a").live('click', function() {
    alert( this.id );
});

Or better, use .delegate() which is similar to .live(), but more efficient.

$(function() {
    $("#sotto_eti").delegate('a', 'click', function() {
        alert( this.id );
    });
});


if you would retrieve the ID of a links added dynamically, you should use the live function instead :

<script>
$("#sotto_eti a").live("click", function()
{
    alert($(this).attr("id"));
});
</script>


    alert($(this).get(0).id);

should work.


Use live() for elements added later:


You need to use live method for dynamic elements:

$("#sotto_eti a").live('click', function()
{
  alert($(this).attr("id"));
});

Here is working demo

Also make sure that you include the jquery library in your page.

0

精彩评论

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