脚本中的函数未被执行(HTML)



我有这个函数"文件名";获取文件名并将所有具有属性CCD_ 1的文本更改为文件名。

例如,在example.html中,<p class='filename'></p>将读取";例如";。

这是我放在body标签末尾的函数(如果有帮助的话,我从这里得到代码(:

<script type="text/javascript">
function filename() {
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.getElementsByClassName("filename").innerHTML = filename;
}
</script>

在example.html中,我添加了代码<title class="filename"></title><p class="filename"></p>,但该函数不起作用。我尝试将onload="filename()"添加到body和head标签中,但没有任何变化。

试试这个:

document.addEventListener('DOMContentLoaded', function() {
filename();
});
function filename() {
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.getElementsByClassName("filename").innerHTML = filename;
}

最新更新