首页 > 解决方案 > 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>

标签: javascriptjquery

解决方案


推荐阅读