jQuery和其他库,以及'$'的用法

dal*_*ard 2 jquery

我有一个快速,初学者类型的问题.如果我使用jQuery和其他一些框架,下面的语句会有问题:

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

也就是说,在.ready()函数中使用'$'.是否应该用'jQuery'代替'$'以避免冲突?

kar*_*m79 6

是的,如果你正在使用另一个使用$的库,你可以使用完整形式的jQuery或在无冲突模式下设置jQuery .例如:

<script>
     jQuery.noConflict();

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

     // Use Prototype with $(...), etc.
     $('someid').hide();
   </script>
Run Code Online (Sandbox Code Playgroud)

在防止与其他库冲突的同时从短名称中受益的另一种方法是做这样的事情:

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

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

     // Use Prototype with $(...), etc.
     $('someid').hide();
</script>
Run Code Online (Sandbox Code Playgroud)

我建议读这个:

http://docs.jquery.com/Using_jQuery_with_Other_Libraries