首页 > 解决方案 > 兼容模式下正确使用JQuery

问题描述

我编写了一个 javascript 类,我使用特定的动态加载版本的 JQuery(版本 3.2.1)。我在兼容模式下使用动态加载的版本。

如果选择器在兼容模式下“生成”并作为参数传递给函数,我不担心,也会使用兼容模式(我自己的版本而不是原始版本)。

这里的代码:

function toggleFunction ( jQuerySelectorItem )
{
    //hide all
    $jq_321(".class").hide();
    
    var checkBoxes = $jq_321(".class[rel-data='" + jQuerySelectorItem.attr("rel-data") + "'] input"); // <<<<< is this 'jQuerySelectorItem' still use jQuery 3.2.1 if generated by '$jq_321' selector ?

    if (jQuerySelectorItem.is(":checked")) 
    {
        checkBoxes.toArray().forEach ( item => this.__changeDependantCheckBoxStatus(item, true));
    } 
    else 
    {
        checkBoxes.toArray().forEach ( item => this.__changeDependantCheckBoxStatus(item, false));
    }
    
    $jq_321(".class[rel-data='" + jQuerySelectorItem.attr("rel-data") + "']").show();
}

这是我在使用它之前以兼容模式动态加载正确版本的 JQuery 的方法:

window.onload = (event) => {
    var jqScriptTag = document.createElement("script");
    jqScriptTag.src = 'https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js';

    jqScriptTag.onload = function() {
        console.log('Temporary jQuery version : ' + jQuery.fn.jquery);
        $jq_321 = jQuery.noConflict(true);

        console.log('Restored original jQuery version : ' + jQuery.fn.jquery);
        //other code that will indeed call toggleFunction when needed
    };

    document.head.appendChild(jqScriptTag);
};

这里是控制台日志:

临时 jQuery 版本:3.2.1

恢复原始 jQuery 版本:1.4.2

标签: javascriptjquerycompatibility

解决方案


.fn.是一种在没有 jquery 对象的情况下访问 jquery 方法的方法,您称之为选择器“生成”

您还可以.fn.在任何 jquery 对象上调用该部分,例如:

console.log($("div").jquery)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div></div>

因此,您可以轻松检查您的 jquery 对象(生成的选择器)是哪个版本:

console.log(d331.jquery)
console.log(d123.jquery)
<div id="div1"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var d331 = $("#div1");
</script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<script>
var d123 = $("#div1");
</script>

只要您的函数使用两者中都存在的 jquery 方法,您就不会遇到问题(在您的函数中)。


推荐阅读