将jQuery转换为无冲突模式 [英] Converting jQuery to no conflict mode

查看:62
本文介绍了将jQuery转换为无冲突模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我正在使用的脚本.

Here's a script I'm using.

$(window).load(function() {
$('#edifici, #artistici, #industriale, #fotovoltaico, #veterinaria, #architettonici').hide();

if (!!window.location.hash) {
    var hash = window.location.hash;
    var $content = $(hash);
    showContent($content)
}

$('.home').click(function () {
    var id = this.id.replace('mostra_', '');
    var $content = $('#' + id + ':not(:visible)');
    if ($('.current').length === 0) {
        showContent($content)
    } else {
        $('.current').fadeOut(600, function () {
            showContent($content)
        });
    }
});

function showContent(content) {
    content.fadeIn(600);
    $('.current').removeClass('current');
    content.addClass('current');
}
});

根据本指南使用在WordPress(无冲突模式下使用jQuery的WordPress)中,我将脚本修改为

As per this guide, to use it in WordPress (which has jQuery in no-conflict mode) I modified my script to

jQuery.noConflict();

jQuery(window).load(function($) {
$('#edifici, #artistici, #industriale, #fotovoltaico, #veterinaria, #architettonici').hide();

if (!!window.location.hash) {
    var hash = window.location.hash;
    var $content = $(hash);
    showContent($content)
}

$('.home').click(function () {
    var id = this.id.replace('mostra_', '');
    var $content = $('#' + id + ':not(:visible)');
    if ($('.current').length === 0) {
        showContent($content)
    } else {
        $('.current').fadeOut(600, function () {
            showContent($content)
        });
    }
});

function showContent(content) {
    content.fadeIn(600);
    $('.current').removeClass('current');
    content.addClass('current');
}
});

不幸的是,它似乎无法正常工作...我在做什么错了?

Unfortunately it doesn't seem to work properly... what am I doing wrong?

推荐答案

jQuery.noConflict();

说明:放弃jQuery对$变量的控制.

这意味着jQuery将不再使用$,因此它将清除与其他库的所有冲突.

This means jQuery will not use $ anymore, so it will clear all conflicts with other libraries.

要在内部使用$,您可以执行以下操作:

To use $ internally you can do the following:

您可以将现有代码包装到匿名函数中,并将jQuery作为参数传递,例如:

You can wrap the existing code into an anonymous function and pass jQuery as an argument, for example:

(function ($) {

    // use $ here
    $('#hello').html('world');

})(jQuery);

或使用jQuery提供的快捷方式:

or use a shortcut offered by jQuery:

jQuery(function($) {

    // use $
    $('#hello').html('world');

});

ready方法还传递了jQuery对象:

ready method also passes the jQuery object:

jQuery(document).ready(function ($) {
    // ...
});

这篇关于将jQuery转换为无冲突模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆