【问题标题】:How to make this code locate frame from previous directory?如何使此代码从上一个目录中定位框架?
【发布时间】:2012-02-28 21:03:04
【问题描述】:

我在网上找到了一个 java 脚本,如果在索引页面框架之外打开,它会重定向页面。这在所有页面都在主目录中时有效,但是当页面在一个目录上时它不起作用。

当我将位置页面用作:index.html 时,页面是否在新选项卡中打开,它不会重定向。

如果我使用 ../index.html,那么每次我尝试单击指向该页面的链接时,它都会刷新我的索引页面。

有什么想法吗?

<!DOCTYPE html>
<html>
    <head>
        <script language="javascript">
            var framespage="index.html"
            if (top.location==document.location)
            {
                top.location=framespage;
            }
            else
            {
                var parent_location=parent.location.href;
                var str_beginning=parent_location.length-framespage.length;
                if (parent_location.substring(str_beginning, parent_location.length)!=framespage)
                {
                    parent.location=framespage;
                }
            }
        </script>
        <link href="../styles.css" rel="stylesheet" type="text/css" />
    </head>
</html>

编辑

我发现了一段代码可以完成这项工作。

我的另一个问题是如何延迟加载页面?我想通知用户用户不打算在框架之外加载页面。

如何延迟页面重定向?

<script language="javascript">
    if (top.location == self.location) 
    {
        top.location = '../index.html'
    }
</script>

【问题讨论】:

  • 我只是想知道为什么我被否决并投票赞成:)

标签: javascript html frame


【解决方案1】:

因此,基本上,如果 parent.location = framespage 不相同,脚本将设置它们,但您遇到的问题是当您的 index.html 文件位于单独的目录中时。

你有几个选择:

  1. index.html 设置为其绝对路径(例如http://www.mywebsite.com/index.html
  2. 确定您在目录结构中的位置并修改framespage 变量。

    var path = document.location.pathname;
    if (path.indexOf('/') !== -1) {
      framespage = '/index.html';
    } else { framespage = 'index.html'; }
    

我想得越多,为什么不添加一个正斜杠,以便它始终指向根。能详细点吗?

【讨论】:

  • 我试图复制并粘贴您的代码,但它返回空白页。
  • 另外,我不能使用绝对路径,因为我没有在线上传这个页面,只是在处理它。
【解决方案2】:

我做了一些搜索,发现了可以完成这项工作的代码:

    <script language="javascript">
        if (top.location == self.location) 
        {
            top.location = '../index.html'
        }
    </script>

【讨论】:

    猜你喜欢
    • 2021-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多