简体   繁体   English

用javascript跳转到命名锚点

[英]jump to named anchor with javascript

I have a php (codeigniter) program that displays all the finished projects of and engineering company. 我有一个php(codeigniter)程序,显示所有已完成的项目和工程公司。 I can click the detail page and from there I can click a link to go back to the overview page. 我可以单击详细信息页面,然后我可以单击链接返回概述页面。 To avoid starting at the top of the list again I would like to jump to the project I cam from. 为了避免再次从列表的顶部开始,我想跳转到我凸出的项目。 It seems easy but it gives me problems. 这似乎很容易,但它给我带来了麻烦。 I found this solution on the Internet that works with Chrome but not with Firefox and IE: 我发现这个解决方案在互联网上适用于Chrome,但不适用于Firefox和IE:

<script type="text/javascript" language="javascript">
    function moveWindow (){window.location.hash="a13";}
</script>
<body onload="moveWindow()">
.
.
.
<a name="a13"></a>

The content of the anchor gets dynamically generated by PHP. 锚的内容由PHP动态生成。 As I said it works in Chrome only. 正如我所说,它仅适用于Chrome。 IE says something like undefined function moveWindow when I go in debug mode. 当我进入调试模式时,IE会说像未定义的函数moveWindow

You can attach a function to the details click that change the URL to currentURL#yourID and then change it to the final URL. 您可以将功能附加到详细信息单击,将URL更改为currentURL#yourID,然后将其更改为最终URL。 This way, currentURL#yourID will be stored in the history of the browser and going back will get you to the right anchor. 这样,currentURL#yourID将存储在浏览器的历史记录中,并返回将使您到达正确的锚点。

Something like (assuming you use jQuery and your IDs are on the <a> ): 类似的东西(假设你使用jQuery,你的ID在<a> ):

$(document).ready( function() {
    $('#yourlist a').click( function(e) {
       e.preventDefault();
       window.location = '#'+$(this).attr('id');
       window.location = this.href; // intentionally not using jQuery ;-)
    });
});

The HTML would look like: HTML看起来像:

<ul id="yourlist">
    <li><a href="details_page_for_item_1.html" id="a1">Item 1</a></li>
    <li><a href="details_page_for_item_2.html" id="a2">Item 2</a></li>
    <li><a href="details_page_for_item_3.html" id="a3">Item 3</a></li>
</ul>

Not tested... 未经测试......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM