2014-06-27 132 views
0

我正在创建一个演示,其中我在URL中添加了一个查询字符串。当我加载我的HTML时,我得到了我的查询的值。我希望如此,如果查询字符串的值为“simple”,它将删除加载的JS文件。如何删除加载的脚本并添加新的脚本?

如果它发现一个非“简单”的值,它应该加载另一个JS文件。

我谷歌搜索它的解决方案,但没有任何工作。

这里是我的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> 
+1

什么是去除JS文件的目的是什么? – Yaje

+0

的目的是,如果它简单(在查询字符串)我想使用该文件。其他我想用其他文件 – Shruti

+1

你可以进一步解释那些“那”文件?它令人困惑 – Yaje

回答

1

可以检查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. 
} 

} 
+0

如何删除js文件。这个函数是麦酒添加。但如何删除加载的文件 – Shruti

+0

其次为什么我downvoted ..我面临一个问题。它不是一个好问题?> – Shruti

+0

在例子中,你只会在检查字符串后立即加载文件,这样你就不需要删除任何 – Yaje