我一直在尝试弄清楚是否可以动态更改 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 动态更改 <script> 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52528498/