开发者

How do you use jQuery .data() to store html?

when I look u开发者_Go百科p the syntax for .data(), it gives examples like this:

$('body').data('foo', 52);

I am doing AJAX loads and I was wondering if it is possible to store the incoming html using .data() so once the content is loaded, I would not need to do another AJAX load if the same link is clicked again - I would check to see if the .data key is empty.

Would something like this work?:

To load the contents of a #ajaxdiv into storage:

$('body').data('storage', div#ajaxdiv.html());

To test if the data has already been loaded:

if $('body').data('storage') != '' {

div#ajaxdiv.html($('body').data('storage'));

}

Thanks in advance!!

Al


Edit: After looking at this again, I'm not really sure why you're storing the data in the body element. Keep in mind that the data() method is not a replacement for all variables-- just data that you want associated with a given element. See my example below for more on this.

It should work fine. The data() method is like storing data into a variable, but that data is now conveniently associated with the element itself.

You should be careful to namespace the key you use for your data, though. In your code, you're using 'storage', but that's awfully generic and seems very susceptible to collisions with other code. I would suggest using a prefix, like: 'blah.storage'.

Also, SLaks was correct-- your selector will need to be passed through jQuery.

// SLaks' correction and my namespace suggestion
$('body').data('blah.storage', $('#ajaxdiv').html());

// Alternative method, where #ajaxLink is the link you click to trigger
// the data retrieval
$('#ajaxLink').bind('click', function (e) {
    e.preventDefault();

    // Notice that we're using $(this).data(), so that our cache is associated
    // with the link element itself.

    if ($(this).data('blah.cachedAjaxHtml')) {
        // The data was found in the cache. Use it to populate the div.
        $('#ajaxDiv').html($(this).data('blah.cachedAjaxHtml'));
    } else {
        // Load the data via AJAX and store it in the cache
        var ajaxResult = whateverYouDoToLoadIt();

        $(this).data('blah.cachedAjaxHtml', ajaxResult);
        $('#ajaxDiv').html(ajaxResult);
    }
}


You need to write $('div#ajaxdiv').html.


$('body').data('storage', div#ajaxdiv.html());

...should be...

$('body').data('storage', $('#ajaxdiv').html());

...and...

div#ajaxdiv.html($('body').data('storage'));

...should be...

$('#ajaxdiv').html($('body').data('storage'));
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜