javascript - 使用 jQuery 动态更改 <script> 标签

标签 javascript jquery

我一直在尝试弄清楚是否可以动态更改 src<script>标签(或加载新的 script 标签)并使之前的脚本不再执行。下面的例子:

index.html

<button id="action">Click</button>

<script id="javascript-file-script" type="text/javascript" src="/js/oldjsfile.js"></script>
<script type="text/javascript">
    $(document).ready(function() {

        $("#javascript-file-script").remove();

        setTimeout(function() {
            $('body').append('<script id="javascript-file-script" src="/js/newjsfile.js" type="text/javascript"><\/script>')
        }, 100);

    });
</script>

oldjsfile.js

$(document).ready(function() {

    console.log('old file loaded');

    $('#action').click(function() {
        alert('old');
    });

});

newjsfile.js

$(document).ready(function() {

    console.log('new file loaded');

    $('#action').click(function() {
        alert('new');
    });

});

在更改 javascript 文件之前,请单击 #action将有 1 个警报“旧”。更改脚本后,单击 #action我收到“旧”和"new"两个警报。有没有办法“卸载”以前的文件,以便原来的click函数被删除/未执行?

我正在寻找除更改 ID 或编辑脚本之外的解决方案。我认为这是不可能的,因为脚本已经在内存中。

最佳答案

这是不可能的。它已经加载并正在运行。您应该考虑使用 .on.off 绑定(bind)到 click 事件。

关于javascript - 使用 jQuery 动态更改 &lt;script&gt; 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52528498/

相关文章:

javascript - 页脚 div 和正文标签之间几乎静态的间隙

javascript - 数组排列函数

jquery - 使用 jQuery getJSON 在 Reddit 上获取 url 的分数

jquery - 事件监听器 : why does only one of the scripts work?

javascript - react native 中的 2 列

javascript - C3-折线图时间序列错误: x is not defined for id = "Dates"

javascript - 当用作函数参数时,Await 函数在函数运行之前不会得到解析

javascript - 如何使 carouFredSel 自动播放和同步?

JQuery 和 IE8、兼容模式和 IE7 模拟

Jquery UI 元素拖放位置在第一次放置时跳转