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

Displaying file name extensions in html using external js

我正在尝试使用 html 和外部 javascript 显示文件扩展名,但我的网站仍然空白。我从另一个 Whosebug 答案中得到了这个示例代码,但我无法让它工作。当我像这样在我的 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>