开发者

Potential Bug with jQuery data() when dynamically chaning attribute?

I have no idea if I just found a potential jQuery bug, but check out the following case.

If I'm dynamically changing a data-ajax-link attribute and then try to get it's value with $('something').data('ajax-link'); the value that's retrieved is still the old one before changing it dynamically.

Here is the example. It's a custom dropDown that sets the clicked option to the first child of the ul. The name of the element as well as the data-ajax-link of the first-child is updated with the values of the clicked option … http://jsfiddle.net/RLF3W/1/

$('.select .option').live('click', function (e) {
    e.stopPropagation();
        $(".select .option:not('.darr')").hide();
        selectedOption = $(this).parents("div.select").find(".option:first");

        $(this).siblings().show();
        selectedOption.text($(this).text()).attr('data-ajax-link', $(this).data('ajax-link'));
});

$('.select .option:not(".darr")').live('click', function () {
    $(this).parents("div.select").find(".option:not('.darr')").hide();
});

$(window).click(function() {
    $(".select .option:not('.darr')").hide();
});


$('a#tester').live('click', function(e) {
    e.preventDefault();

    //var sort = $('#sortb .darr').attr('data-ajax-link');
    var sort = $('#sort .darr').data('ajax-link');

    $('#output').text(sort)

});

In my example you can see that after selectin开发者_开发百科g a different option in the dropdown and then hit the test link the value of the data-ajax-link is still the original value, even though it's actually changed if the element is inspected. If I use .attr('data-ajax-link') to get the updated value it works fine.

Am I wrong here and I'm doing something wrong or is this a bug?


You're setting it using .attr(), but getting it using .data().

I'm pretty sure that when getting via .data(), it first looks at its data in jQuery.cache to see if the property exists. Then if not, it looks for an attribute.

You should just send it via the data- attribute but use .data() to get and set.

Change this:

selectedOption.text($(this).text()).attr('data-ajax-link', $(this).data('ajax-link'));

to this:

  // Use .data()----------------------v
selectedOption.text($(this).text()).data('ajax-link', $(this).data('ajax-link'));

Example: http://jsfiddle.net/RLF3W/5/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜