2009-07-21 43 views
2

我有一個快速,初學者類型的問題。如果我是使用jQuery和一些其他的框架,將下面的語句是有問題的:

jQuery(document).ready(function() { 
    $("input[name='password']").focus(function() { 
     $("input[value='login']").attr("checked", "checked"); 
    }); 
}); 

也就是說,。就緒()函數中使用「$」的。爲避免衝突,'$'應該替換爲'jQuery'嗎?

+0

http://stackoverflow.com/questions/1049112/what-is-the-in-jquery/1050433#1050433 – SilentGhost 2009-07-21 11:25:52

+0

@SilentGhost,謝謝。我正在尋找一個類似的問題,以便再次詢問同樣的事情,但找不到任何東西。 – dalizard 2009-07-21 12:04:10

回答

2

當使用多個庫,利用$,常見的做法是使用noConflict模式,並重新分配$ jQuery的一種東西。

var $jq = jQuery.noConflict(); 

$jq(function() { 
    $jq("input[name='password']").focus(function() { 
     $jq("input[value='login']").attr("checked","checked"); 
    }); 
}); 

在插件開發中,處理此問題的常用方法是將`$'作爲參數傳遞給定義插件定義的函數,並將函數應用於jQuery對象。

;(function($) { 
    ... 
})(jQuery); 
6

是的,如果您使用另一個使用$的庫,則可以使用完整的jQuery形式或在no-conflict mode中設置jQuery。例如:

<script> 
    jQuery.noConflict(); 

    // Use jQuery via jQuery(...) 
    jQuery(document).ready(function(){ 
     jQuery("div").hide(); 
    }); 

    // Use Prototype with $(...), etc. 
    $('someid').hide(); 
    </script> 

另一種方法是從一個簡短的名字中獲益,同時防止與其他圖書館衝突是做財產以後這樣的:

<script> 
    var $j = jQuery.noConflict(); 

    // Use jQuery via $j(...) 
    $j(document).ready(function(){ 
     $j("div").hide(); 
    }); 

    // Use Prototype with $(...), etc. 
    $('someid').hide(); 
</script> 

我建議閱讀本:

http://docs.jquery.com/Using_jQuery_with_Other_Libraries

1

你已經顯示的是正確的,除了你想要替換所有實例'$'。您將會覆蓋'$'功能。

jQuery(document).ready(function() { 
    jQuery("input[name='password']").focus(function() { 
     jQuery("input[value='login']").attr("checked", "checked"); 
    }); 
}); 
1

當然,儘可能明確地使您的代碼 - 特別是在這種情況下。如果網站稍後改變,最終可能會調用錯誤的庫。

1

你可以用你的jQuery代碼的一部分進入功能如下:

function($) { 
    // jQuery code here 
}(jQuery); 

// use $ here to access other JS library 

,你將能夠使用$函數內(這是自動執行功能映射$ jQuery的

1
jQuery(document).ready(function ($) { 
    $("input[name='password']").focus(function() { 
     $("input[value='login']").attr("checked", "checked"); 
    }); 
}); 

回調就緒()接收的jQuery作爲參數:您可以撥打這個說法$。這將覆蓋回調範圍內的其他$定義。

相關問題