如何将此jquery代码转换为noconflict

时间:2010-04-27 10:10:47

标签: javascript jquery css xhtml

我们是否必须用jquery替换每个$?

$(document).ready(function() {

    $('.tabs a').click(function(){
        switch_tabs($(this));
    });

    switch_tabs($('.defaulttab'));

});

function switch_tabs(obj)
{
    $('.tab-content').hide();
    $('.tabs a').removeClass("selected");
    var id = obj.attr("rel");

    $('#'+id).show();
    obj.addClass("selected");
}

3 个答案:

答案 0 :(得分:2)

只要您确定该片段仅包含jQuery的jQuery用法,那么您可以将其包装在闭包中

(function($){
    $(document).ready(function() {

        $('.tabs a').click(function(){
            switch_tabs($(this));
        });

        switch_tabs($('.defaulttab'));

    });

    function switch_tabs(obj)
    {
        $('.tab-content').hide();
        $('.tabs a').removeClass("selected");
        var id = obj.attr("rel");

        $('#'+id).show();
        obj.addClass("selected");
    }
})(jQuery);

答案 1 :(得分:1)

使用

$.noConflict();


(function($) { 
  $(function() {
    // more code using $ as alias to jQuery
  });
})(jQuery);
// other code using $ as an alias to the other library

解决冲突问题

更多细节:http://api.jquery.com/jQuery.noConflict/

答案 2 :(得分:0)

var $j = jQuery.noConflict();


$j(document).ready(function() {

$j('.tabs a').click(function(){
    switch_tabs($j(this));
});

switch_tabs($j('.defaulttab'));

});

function switch_tabs(obj)
{
$j('.tab-content').hide();
$j('.tabs a').removeClass("selected");
var id = obj.attr("rel");

$j('#'+id).show();
obj.addClass("selected");
}