On my page most p-sections under a h3-heading are hidden. If you click on them, the content beneath is shown. Only the first section is shown when the page is opened. I use jQuery to hide these section like:
jQuery("#area h3:first").addClass("active");
jQuery("#area p:not(:first)").hide();
But what, if there is an anchor in one of the other section and the user is linking to it with a # at the end of the url? Right now, it jumps to the hidden section, which is irritating, because the text is not shown. I would not like to hide the section when an anchor in the url is within this section e.g. http://domain.com/page.php#anchor_in_section_3.
How do I prevent the section to hide/collapse?
Detail: After answer 1 I found two problems: If you use .hide and a .show just one line of code later, the sections remains hidden. That seems to fast for jQuery. The other problem is, that with the solution described in answer 1 jQuery only finds the anchor, if it is not in a child tag.
It is more difficult than I thought :)
So the solution described in words is, that all sections except the first an开发者_如何学运维d the one containing the anchor tag should be hidden. The anchor can be in any (child)-tag of the section.
Tried 2 hours to transfer this into jQuery but without success with my poor jQuery-knowledge.
To get the name of the anchor from the URL, use the following line:
var anchorName = document.location.hash.substring(1)
That retrieves the hash portion of the URL, then trims the first character out (the first character will always be the hash symbol, "#"). Here's some documentation on that: Javascript Tutorial, Location.hash. Once you have that, do something like the following:
jQuery("#area p:has(a[name=" + anchorName + "])").show();
This will show any paragraph in #area
that contains an anchor with the name specified in the URL's hash portion.
EDIT
To solve the problem of jQuery being to fast, you can use a fancier selection to only hide the ones that will end up hidden, like so:
$("#area > p:not(:first)").filter("p:not(:has(a[name=" + anchorName + "]))").hide();
That says to take all paragraphs except the first one, then take the subset of those that don't contain an anchor with a given value for the name
attribute, and hide whatever remains. The first paragraph, and any that contain an anchor with the give name will remain visible.
Here is a live demo: http://jsfiddle.net/JDQxP/
Because we can't get the hash from the URL on jsFiddle, I've replaced that line with static values. Uncomment them one at a time to see the effect of each. Note that the "phasellus" anchor is in a wrapper span, but the selector still works properly on it.
精彩评论