gpt4 book ai didi

javascript - 使用 Jquery 动态删除脚本标签时出现问题

转载 作者:行者123 更新时间:2023-11-30 14:24:45 24 4
gpt4 key购买 nike

我创建了两个简短的 javascript 文件,每个文件都包含一个 $(document).ready 函数,该函数具有 javascript 来检测包含它的 html 文件中的按钮点击。我的主 html 文件具有指向 header 中每个文件的脚本标记:

file1.js:

$(document).ready(function(){
$('.wrapper').on('click', '.click_1', function(){
alert('hello from the first file');
});
});

file2.js:

$(document).ready(function(){
$('.wrapper').on('click', '.click_2', function(){
alert('hello from the second file');
});
});

但是,我的目标是能够从 header 及其功能中动态删除其中一个脚本标记(第二个文件中的 javascript)。为此,我在我的主 html 文件中创建了一个脚本,以通过 src 属性删除目标脚本标签。然而,虽然对页面源代码的检查显示第三个脚本标签确实已被删除,但其功能仍然存在。例如,即使在单击 .remove_2 按钮后,我仍然可以单击 .click_2 按钮并收到 “hello from the second file”警报:

main.html:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="file1.js"></script>
<script type="text/javascript" src="file2.js"></script>
</head>
<body>
<div class="wrapper">
<button class='click_1'>File1</button>
<button class='click_2'>File2</button>
<button class='remove_2'>Remove File2</button>
</div>
</body>
<script>
$(document).ready(function(){
$('.wrapper').on('click', '.remove_2', function(){
$('script[src="file2.js"]').remove();
});
});
</script>
</html>

总之,我希望能够动态的去掉一个script标签,让该标签指向的文件中的javascript不再对html页面产生任何影响。但是,我无法做到这一点。谁能告诉我我的代码有什么问题?另外,我想要完成的事情甚至可能吗?谢谢。

最佳答案

删除外部脚本不会删除事件处理程序。它们附在当前文档中。

解决方案可以是:

  1. 删除脚本
  2. 获取所有html页面
  3. 用新内容替换 html 页面

    $('.wrapper').on('click', '.remove_2', function(){
    $('script[src="file2.js"]').remove();
    var html = document.documentElement.innerHTML;
    document.open('text/html');
    document.write(html);
    document.close();
    });

在 jQuery 中,删除脚本后仅替换 header :

$('.wrapper').on('click', '.remove_2', function(){
var header = $('html head');
header.find('script[src="file2.js"]').remove();
$('html head').replaceWith(header);
});

关于javascript - 使用 Jquery 动态删除脚本标签时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52130255/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com