javascript - jQuery异步时如何在窗口范围内使用jQuery代码
问题描述
这是我们正在使用的代码的简化版本。目的是让 jQuery 异步加载,并能够在 doSomething() 函数中使用 jQuery 引用。如果 doSomething() 函数在“onload”函数中编码,则它不再在窗口的范围内,并且“A”链接失败。
但是,如果 doSomething() 函数是在主文档中编码的,jQuery 可能会也可能不会在 DomContentLoaded 之前加载。
<a href="javascript:doSomething()">Do it</a>
<script>
function doSomething(){
$("#aaaa").fadeIn( "slow", function(){});
}
</script>
<script src="jquery.js" async id="jQ"></script>
<script>
document.getElementById("jQ").onload = function(){
doSomething();
}
</script>
感谢@skobaljic 和@vitkarpov,您的解决方案奏效了。
新的工作代码:
<span id="cob1" data-action="args1">Do it</span>
<span id="cob2" data-action="args2">Do it again</span>
<script src="jquery.js" async id="jQ"></script>
<script>
document.getElementById("jQ").onload = function(){
$("#cob1,#cob2").click(function(a){
a = $(this).attr('data-action');
$("#" + a).fadeIn( "slow", function(){});
});
}
</script>
解决方案
推荐阅读
- javascript - 如何使用 JS DOM 修改 CSS 属性?
- python - 通过 YouTube 数据 API 上传大视频时出现 Python MemoryError
- litedb - 通过 C# 进行简单的 LiteDB 查询(我在苦苦挣扎!)
- git - 为什么`git update-index`不会影响不在当前目录中的文件?
- azure-devops - Azure devops 抱怨语法循环
- sql-server - SSRS 报表界面加载时间长,仅在一个环境中
- python - InvalidArgumentError:断言失败:[无法将字节解码为 JPEG、PNG、GIF 或 BMP]
- html - 缩放网页超过 100% 会弄乱整个文本
- c - 调用函数时出现分段错误
- jenkins - Jenkins slave 作为 kubernetes pod