gpt4 book ai didi

javascript - 如何删除加载的脚本并添加新脚本?

转载 作者:行者123 更新时间:2023-12-03 12:21:08 25 4
gpt4 key购买 nike

我正在创建一个演示,其中我在 URL 中添加了一个查询字符串。当我加载 HTML 时,我得到了查询的值。我想要这样,如果查询字符串的值为“simple”,它会删除加载的 JS 文件。

如果它发现“simple”以外的值,它应该加载另一个 JS 文件。

我在 Google 上搜索了解决方案,但没有任何效果。

这是我的 HTML:

<!DOCTYPE html>
<html>
<head>
<script src="js/jquery-1.11.0.min.js" type="text/javascript"></script>
<script src="js/copynode.js" type="text/javascript" id="dynamic_files"></script>
<script type="text/javascript">

$(window).load(function(){
// full load
var query = decodeURIComponent(window.location.search.substring(1));
console.log("---------------------");
var index=query.indexOf("=")
query=query.substr(index+1,query.length);
console.log(query);
if(query=="simple"){
alert('if--');
//$('#dynamic_files').remove();
}else{
alert('else--');
$('#dynamic_files').remove();
var script = document.createElement('script');
script.src = 'js/index.js';
document.getElementsByTagName('div')[0].appendChild(script);
}

});

</script>
</head>

<body >
<h1>My Web Page</h1>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="loadScript()">Load Script</button>
</body>
</html>

最佳答案

您可以先检查String的值,然后编写一个函数,如下所示:

function checkString(){
if($('#ID_OF_ELEMENT_OF_THE_STRING').value == "simple"){
//load the script needed
var head = document.getElementsByTagName('head').item(0);
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', 'http://mysite/my.js');
head.appendChild(script);
}else{
//load the other part.
}

}

关于javascript - 如何删除加载的脚本并添加新脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24446439/

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