2013-06-12 27 views
0

:刪除所有參考noconflict固定問題2腳本解決抵消互相

我有2個腳本(A部分和B部分),它很好地工作在那裏自己該做的2個獨立的任務。當我把它們放在一個頁面上時,一個取消另一個。任何幫助讚賞。

// PART A 
var $j = jQuery.noConflict(); 
jQuery(function ($j) { 

var image_slides = []; 

image_slides.push({ 
image: 'img/background.jpg' 
}) 

$j.supersized({ 

min_width: 0, 
min_height: 0, 
vertical_center: 1, 
horizontal_center: 1, 
fit_always: 0, 
fit_portrait: 1, 
fit_landscape: 0, 
slides: image_slides, 
}); 
}); 

// PART B 
function cent() { 
var $block = $("#block"), 
    margintop = parseInt($block.height()/-2); 
console.log('called'); 
$('#block').css("margin-top", margintop); 
}; 

$(document).ready(function(){ 
cent(); 
}); 
$(window).resize(function(){ 
cent(); 
}); 
+2

這是因爲你正在調用'noConflict',它將'$'作爲別名去除到'jQuery'中。 – zzzzBov

+0

在這種情況下,刪除PART A將允許B部分工作:http://jsfiddle.net/njs2p/19/ – user2478466

+0

'jQuery(function($ j){'在這種情況下沒有任何意義,您已經重新定義了您的jQuery對象作爲'$ j',因此你可以做'$ j(function(){' –

回答

1

裹B部分中的另一個函數調用來代替$變量:

(function($) { 
    // Part B 
})(jQuery); 
0

的jQuery.noConflict() - 調用返回全局變量$分配給它的原始定義的jQuery被初始化之前。例如,你可能會在你的頁面上加載另一個庫/方法/屬性,在$中存儲對自身的引用。因此,B部分中使用的所有特定於jQuery的方法都需要在變量$ j而不是$上調用。

正如Joe Frambach所回答的那樣:您可以將B部分代碼包裝在一個將jQuery對象傳遞給定義爲「$」的參數中的方法中。這裏的原因:

var $j = jQuery.noConflict(); // return reference of $ to original assignment 

// calls to $ here are made in the global namespace, and not invoked on jQuery 
// due to the noConflict-invocation above 

(function($) { 

    // all calls to $ inside this function body are now invoked on jQuery as 
    // jQuery is passed as an argument and we're now referencing a local namespace 

})(jQuery); 

// outside of the above function body calls to $ are made on the global namespace 
// and thus not invoked on jQuery due to noConflict-invocation 

謹防集成使用「noConflict」時被一個jQuery的特定背景寫的(外部)腳本,如實施可能需要一些工作。