开发者

jQuery: Global Variable Namespace Problem

Is there a way to declare a global variable in jQuery in its own namespace?

Sure, I can declare global variables with plain old JavaScript, but they will fall in the window's namespace. For example, if I had a variable named document, it would surely overwrite the document object of the window.

Does jQuery have a hash ta开发者_高级运维ble that lets you store any object by their name?

Thanks.


Not sure why you want to use jQuery for that? You could just create your own namespace:

var namespace = {
    document : "Foo"
};

Please elaborate, if there's some need to use jQuery somehow.


Of course you can. Create a namespace as an object and then attach it to the jQuery function.

(function ($) {

  $.myNamespace = {};

})(jQuery);

Here I've created an auto-executing anonymous function to do the work. I can then add other propertes and functions to the namespace inside this function. Also this avoids the problem of someone else renaming $ to something else.

After this is done you can refer to your namespace as jQuery.myNamespace


If the variable is something that want to associate with an element to be used later, maybe in a different routine, you could use jQuery's "data" method to store it.

e.g.

    :
    :

// Save original HTML content.

var old_html = $('#box').html();
$('#box').data({originalContent: old_html});

// Replace with new content.

$('#box').empty().html(new_html);

    :

// Restore original content (maybe in a different function).

var orig_html = $('#box').data('originalContent');
$('#box').empty().html(orig_html);

    :

I hope this is useful to you.

Regards Neil

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜