?
本文檔使用 php中文網(wǎng)手冊(cè) 發(fā)布
可創(chuàng)建一個(gè)新的jQuery副本,不影響原有的jQuery對(duì)像。
有兩個(gè)具體使用jQuery.sub()創(chuàng)建案例。首先是提供完全沒(méi)有破壞jQuery原有一切的方法,另一個(gè)用于幫助做jQuery插件封裝和基本命名空間。
請(qǐng)注意,jQuery.sub()不會(huì)做任何特殊的隔離 - 這不是它的意圖。所有關(guān)于jQuery的sub'd版本的方法將仍然指向原來(lái)的jQuery。(綁定和觸發(fā)仍將通過(guò)主jQuery的事件,數(shù)據(jù)將通過(guò)主綁定的元素的jQuery,Ajax的查詢(xún)和活動(dòng)將通過(guò)主jQuery的運(yùn)行,等等)。
請(qǐng)注意,如果你正在尋找使用這個(gè)開(kāi)發(fā)插件,應(yīng)首先認(rèn)真考慮使用一些類(lèi)似jQuery UI widget工廠(chǎng),這兩個(gè)狀態(tài)和插件管理子方法。 使用jQuery UI widget的一些例子建立一個(gè)插件。
這種方法的具體使用情況下可以通過(guò)一些例子最好的描述。
該方法是在jQuery 1.5中引入的,但是被證明不是很有用,將被移到j(luò)Query 1.9兼容性插件中。
添加一個(gè)jQuery的方法,以便它不會(huì)受到外部分:
(function(){ var sub$ = jQuery.sub(); sub$.fn.myCustomMethod = function(){ return 'just for me'; }; sub$(document).ready(function() { sub$('body').myCustomMethod() // 'just for me' }); })(); typeof jQuery('body').myCustomMethod // undefined
改寫(xiě)一些jQuery的方法,以提供新的功能。
(function() { var myjQuery = jQuery.sub(); myjQuery.fn.remove = function() { // New functionality: Trigger a remove event this.trigger("remove"); // Be sure to call the original jQuery remove method return jQuery.fn.remove.apply( this, arguments ); }; myjQuery(function($) { $(".menu").click(function() { $(this).find(".submenu").remove(); }); // A new remove event is now triggered from this copy of jQuery $(document).bind("remove", function(e) { $(e.target).parent().hide(); }); }); })(); // Regular jQuery doesn't trigger a remove event when removing an element // This functionality is only contained within the modified 'myjQuery'.
創(chuàng)建一個(gè)插件,它返回插件的具體辦法。
(function() { // Create a new copy of jQuery using sub() var plugin = jQuery.sub(); // Extend that copy with the new plugin methods plugin.fn.extend({ open: function() { return this.show(); }, close: function() { return this.hide(); } }); // Add our plugin to the original jQuery jQuery.fn.myplugin = function() { this.addClass("plugin"); // Make sure our plugin returns our special plugin version of jQuery return plugin( this ); }; })(); $(document).ready(function() { // Call the plugin, open method now exists $('#main').myplugin().open(); // Note: Calling just $("#main").open() won't work as open doesn't exist! });