php 文件中的锚链接指向 index.html


Anchor links in php file point to index.html

我有一个文件index.php主要包含HTML和一些PHP。我已经为某些元素(例如,<h2 id="contact">Contact</h2>)声明了id s,并提供指向它们的链接(参见下文)。

<ul>
  <li><a href="#contact">Contact</a></li>
</ul>

链接在单击时工作正常(即,用户被带到锚点),但它们指向例如index.html#contact,因此当重新加载页面时,您会收到 500 错误。

如何避免这种行为?为什么会这样呢?

顺便说一句,我正在使用 YAML CSS 框架。

您可以使用javascript滚动元素,这样URL就不会更改,并且当您重新加载页面时,该页面具有起始URL。

尝试使用这个:

<ul>
  <li><a href="#contact">Contact</a></li>
</ul>
<h2><a id="contact">Contact</a></h2>

<script>
    function getPosition(element){
        var e = document.getElementById(element);
        var left = 0;
        var top = 0;
        do{
            left += e.offsetLeft;
            top += e.offsetTop;
        }while(e = e.offsetParent);
        return [left, top];
    }
    function jumpTo(id){    
        window.scrollTo(getPosition(id));
    }
</script>
<ul>
<li><a href="#" onclick="jumpTo('contact');">Contact</a></li>
</ul>
<h2><a href="#" id="contact">Contact</a></h2>

更新:你为什么不用js :)破解它

location.replace("http://www.w3schools.com");

更新结束

链接内的哈希 (#) 表示同一页面中元素的"ID"。

href="#id" .. means index.php/#id <-- scroll to an id element
href="link" .. means index.php/link <-- redirect to file called 'link'

您还需要在htaccess中启用重定向到没有文件扩展名的文件。 例如.php/html

您的问题

检查您现有的 htaccess

这很奇怪,因为它应该有效。正如其他人建议的那样,请查看您的错误日志。同时,您可以尝试以下快速修复:

无需在<a>#contact,您可以使用php的帮助放置完整的url,如下所示:

<html>
<head>...</head>
<body>

    <ul>
      <li><a href="<?php echo getPageUrl(); ?>#contact">Contact</a></li>
    </ul>
    <h2 id="contact">Contact</h2>

</body>
</html>
<?php
    function getPageUrl(){
        return 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    }
?>

这应该使您的<a>看起来像这样

<a href="http://example.com/index.php#contact">Contact</a>