首页 > 解决方案 > 使用外部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;
}

标签: javascriptfile-extension

解决方案


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

  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>


推荐阅读