簡體   English   中英

如何使外部js文件寫入html <script> tags? Via plain JS or jQuery

[英]How to make an external js file write to the html <script> tags? Via plain JS or jQuery

我正在嘗試在鏈接到index.html的外部javascript文件中編寫函數,該文件稱為writes; 例如在第18行的index.html文件中的<script></script>標記之間。是否可以使用純Javascript或jQuery做到這一點? 如果是這樣,怎么辦?

編輯:我想在index.html中只有一個腳本標簽。

 function writeToScriptTags() { // this function should write alert("Hello") to the <script></script> tags in the index.html file. } 
 <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <!-- Dependencies --> <script src="https://code.jquery.com/jquery-3.3.1.min.js" charset="utf-8"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" charset="utf-8"></script> <script src="https://code.jquery.com/color/jquery.color-2.1.2.min.js" charset="utf-8"></script> <title>CodeDragon</title> <link rel="stylesheet" href="/css/master.css"> </head> <body> <div id="Dragon"></div> <input type="text" name="_input" value="" id="_input"> <script src="script.js" charset="utf-8"></script> <script> // Javascript file should write alert("Hello") here </script> </body> </html> 

您可以這樣嘗試說這是您的external.js文件

function writeToScriptTags() {
  // this function should write alert("Hello") to the <script></script> tags in the index.html file.
}

您可以通過這種方式在index.html文件中的標簽之間調用external.js文件的函數。

$.getscript("path/to/jsFile", function() {
    writeToScriptTags()
});

希望你能有個主意。

如果腳本標記已經存在,則可以將其text / textContent / innerText值設置為要執行的任何代碼。 但是腳本需要事先為空,即沒有文本,甚至沒有空格,否則它將無法運行。

//use an appropriate css selector to find the correct script
//this just selects the first script it finds
var s = document.querySelector('script');
s.text = 'alert("Here")';

最好只創建一個新的script元素並向其中添加代碼,因為那樣您就不必擔心是否已經使用過script標簽了。

var s = document.createElement('script');
document.head.appendChild(s);
s.text = 'alert("Here")';

當然,如果腳本是使用src屬性設置的,那么腳本的文本將不會運行任何代碼,因為外部鏈接的腳本元素會忽略該代碼。

jQuery解決方案:

$('script').html('alert(\'Hello\')');

純JS解決方案:

document.querySelector('html').innerHTML = alert('Hello');

不要將其作為文本添加到代碼中,因為它將被呈現為純文本並且沒有任何功能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM