How to implement displaying the requested named anchor using JQuery / JavaScript / CSS

放肆的年华 提交于 2020-01-23 03:07:46

问题


The page has a container div which holds multiple content divs. Each content div has a named anchor. Only one of the content divs is displayed at a time:

Example:

<style>
  .lurk { display: none; }
</style>
<div class="container">
  <div id="c1">
    <a name="#c1">One</a> is the loneliest number.
  </div>
  <div id="c2" class="lurk">
    <a name="#c2">Two</a> is company.
  </div>
  <div id="c3" class="lurk">
    <a name="#c3">Three</a> is a crowd.
  </div>
</div>
<script>
// ... something that adds and removes the lurk class from the content divs
</script>

The desired behavior is that if someone requests the page using a valid named anchor in the URL, the JavaScript / JQuery will see it and set the various display properties appropriately so that the content corresponding to the named anchor is visible.

  1. Is the requesting URL available to JQuery?
  2. Is checking for named anchors in the URL usually done early in $(document).ready?()
  3. Is this hard to get right in a cross-browser way?
  4. Is there a library routine for extracting the anchor from an URL, or does everybody roll their own regular expression?

回答1:


You can use location.hash to retrieve the anchor from the URL. This will work across browsers and will work in $(document).ready.

For example:

$("div.container > div").removeClass("lurk");
if (location.hash)
    $("#" + location.hash).addClass("lurk");


来源:https://stackoverflow.com/questions/879910/how-to-implement-displaying-the-requested-named-anchor-using-jquery-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!