javascript - 兼容模式下正确使用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
解决方案
这.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 方法,您就不会遇到问题(在您的函数中)。
推荐阅读
- java - Map-reduce 使用 java - java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:0
- php - 提交后如何保持下拉菜单显示所选选项?
- python - 替换列表中每个项目中未知的第一个字符时键入错误
- r - R tidyr extract doesn't capture multiline expressions
- android - Can't see anything on Android Studio preview and device
- security - 在一个vue应用的登录页面隐藏app.js中的其他代码
- python - 如何将运行for循环的结果存储在不同的文件中?
- python - 具有线性下降和多元数据的梯度下降函数导致空值
- gams-math - 如何在游戏中的单个方程中设置单个变量的下限和上限
- node.js - 为什么 brew 说 nodejs 已安装?