开发者

How do I access an attribute in an event handler?

Why does the following code produce two different alerts? I'm trying to add the "myAttr" attribute using Jquery, but it's value is not available inside the live click handler.

$("#holder").append("<div class='varInfo' myAttr='1'>new</div>")
    .attr("myAttr","a1")
    .click(function(){
        alert($(this).attr("myAttr"));
    });

$(".varInfo").live('click',function(){
    alert($(this).attr("m开发者_运维问答yAttr"));
});


Because in the first code block, you are setting the "myAttr" attribute on #holder, not on div.varInfo. You are also seeting the click handler on #holder. You need to append .varInfo, and then find it.

$("#holder").append("<div class='varInfo' myAttr='1'>new</div>")
    .find('.varInfo')
    .attr("myAttr","a1")
    .click(function(){
        alert($(this).attr("myAttr"));
    });

$(".varInfo").live('click',function(){
    alert($(this).attr("myAttr"));
});

I'd actually recommend switching it up a bit like this if you can:

$('<div class="varInfo" myAttr="1">new</div>')
    .attr('myAttr', 'a1')
    .click( function() {
        alert( $(this).attr('myAttr') );
    })
    .appendTo('#holder');

$(".varInfo").live('click',function(){
    alert($(this).attr("myAttr"));
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜