Javascript 函数在测试站点和实时站点上返回不同的结果

Javascript function returns different results on test site and live site

本文关键字:站点 返回 结果 实时 函数 测试 Javascript      更新时间:2023-09-26

这是我的第一篇文章。我对javascript相当陌生,并且试图使用以下函数来获取文档名称(由页面上的元素ID模仿)以在以后的函数中使用。 在测试现场,它运行良好。 例如,如果文件http://testserver/options/example.html则返回"example"

一个实时站点,它总是返回www

<script  type="text/javascript">  
  $(document).ready(function() {
    var pageName = function() {
    //this gets the full url
    var url = document.location.href; 
    //this removes the anchor at the end, if there is one
    url = url.substring(0, (url.indexOf("#") == -1) ? url.length : url.indexOf("#")); 
    //this removes the query after the file name, if there is one
    url = url.substring(0, (url.indexOf("?") == -1) ? url.length : url.indexOf("?")); console.log(url);
    //this removes the file extension, if there is one 
    url = url.substring(0, (url.indexOf(".") == -1) ? url.length : url.indexOf(".")); console.log(url);
    //this removes everything before the last slash in the path
    url = url.substring(url.lastIndexOf("/") + 1, url.length); console.log(url);
    //return
    return url; console.log(url);
    }
}); 
</script>

尝试像这样修改此行:

您的测试站点不像实时站点那样具有所有"."(即 www. 或 .com)。通过使用lastIndexOf,您可以在扩展名之前的URL中获取"."的最后一个实例。

将其从:

url = url.substring(0, (url.indexOf(".") == -1) ? url.length : url.indexOf("."));

自:

url = url.substring(0, (url.lastIndexOf(".") == -1) ? url.length : url.lastIndexOf("."));

有关lastIndexOf的更多信息,请访问此链接:

lastIndexOf() on MDN

希望这有帮助。