我希望能够在HTML文件的运行文本中插入文件名,例如,在文件"example1.html“中,文本将显示为"This file is example1",在"example2.html”中,将显示为"This file is example2“。这两个文件将具有完全相同的代码。
从here中,我得到了这段代码,它获得了一个超文本标记语言文件的名称:
<title id="title">This is replaced by the filename</title>
<script type="text/javascript">
var url = window.location.pathname; // gets the pathname of the file
var str = url.substring(url.lastIndexOf('/')+1); // removes everything before the filename
str = str.substring(0, str.length - 5); // removes the extension
var filename = str.replace(/%20/g, " "); // if the filename has multiple words separated by spaces, browsers do not like that and replace each space with a %20. This replace %20 with a space.
document.getElementById("title").innerHTML = filename;
</script>我怎样才能把它变成一个在任何地方都可以在任何html文件中使用的函数,我该如何使用它(原谅我对这门语言几乎不存在的知识)?我希望函数是在script.js上,而不是在每个html文件上。
发布于 2021-06-14 22:25:45
您只能通过使用<script>标签或从URL导入脚本来将JS脚本引入页面。您可以尝试将示例中脚本标记内的所有代码移动到一个单独的.js文件中,然后使用<script src='http://yoururl.com/script.js'/>
https://stackoverflow.com/questions/67972018
复制相似问题