cammil
cammil

Reputation: 9899

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("myAttr"));
});

Upvotes: 0

Views: 172

Answers (1)

Jeff
Jeff

Reputation: 4146

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"));
});

Upvotes: 1

Related Questions