加载页面时Javascript函数不起作用

时间:2016-01-10 19:42:55

标签: javascript html css

我不熟悉JavaScript,但在 .htm 文件中包含以下代码。该功能似乎不应该被调用;在直接打开页面时应该调用它,即

www.site.com/12345.htm 

将网址更改为

site.com/#12345.htm

并加载相关脚本和css。

除非直接打开,否则不应该调用它。即访问www.site.com/不应该称之为 index.htm 已经立即加载了css /脚本

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title> Introduction </title>
<script type="text/javascript">
    function isTOCLoaded() {
        //this function for loading the topic within the application if loaded by itself
        //i.e. open the topic .htm file or as search engines link
        var url = window.location.href;
        var baseUrl = url.substring(0, url.lastIndexOf("/") + 1);
        var topicFile = url.substring(url.lastIndexOf("/") + 1)
        var newUrl = baseUrl + "#" + topicFile;
        location.href = newUrl;
        return false;
    }
</script>
</head>
<body>
<h1 id="t57117" class="heading1">Introduction</h1>

<input id="topicId" type="hidden" value="57117" />
<input id="topicDescription" type="hidden" value="Introduction" />
<input id="footer-modified" type="hidden" value="Last modified: 17/12/2015 8:18:59 a.m." />
</body>
</html>

1 个答案:

答案 0 :(得分:3)

如果要对其进行评估,则必须调用函数:

<title> Introduction </title>
<script type="text/javascript">
    function isTOCLoaded() {
        //this function for loading the topic within the application if loaded by itself
        //i.e. open the topic .htm file or as search engines link
        var url = window.location.href;
        var baseUrl = url.substring(0, url.lastIndexOf("/") + 1);
        var topicFile = url.substring(url.lastIndexOf("/") + 1)
        var newUrl = baseUrl + "#" + topicFile;
        location.href = newUrl;
        return false;
    }

    // ADDED: run the function
    isTOCLoaded();
</script>
</head>

在JavaScript中,function关键字用于声明一个函数供以后使用,它实际上不会在第一次调用函数时运行函数的内容。