使用外部js在html中显示文件扩展名



我试图使用html和外部javascript显示文件扩展名,但我的网站仍然是空白的。我从另一个stackoverflow答案中得到了这个示例代码,但我无法使它发挥作用。当我像这样调用html中的函数时,不应该显示变量的扩展吗?

<script>getExtension(file1);</script>

js

var file1 = "index.php";
var file2 = "test.js";
function getExtension(filename) {
return filename.substring(filename.lastIndexOf('.')+1, filename.length) || filename;
}

您正确地获得了扩展,但没有将其写入任何地方的输出中。有不同的方法来输出值,这里有两种可能性:

  1. document.write()
    Document.write()方法将文本字符串写入文档流。但是要小心,对已关闭(加载(的文档调用document.write会自动调用document.open,这将清除文档

var file1 = "index.php";
var file2 = "test.js";
function getExtension(filename) {
return filename.substring(filename.lastIndexOf('.')+1, filename.length) || filename;
}
// This will add "php" to the document
document.write(getExtension(file1));
// This will clear the document and replace it with "js" - added 1 second delay to visualize it
window.onload = function () {
setTimeout(  'document.write(getExtension(file2))', 1000 );
}
<h1>My content</h1>

  1. createTextNode()+appendChild()
    您还可以创建一个文本节点并将其附加到正文中。当然,您也可以创建任何其他元素,并将其添加到您想要的任何位置

var file1 = "index.php";
var file2 = "test.js";
function getExtension(filename) {
return filename.substring(filename.lastIndexOf('.')+1, filename.length) || filename;
}
// Create a text node
var t = document.createTextNode(getExtension(file1));
// Append it to the body
document.body.appendChild(t);
<h1>My content</h1>

最新更新