Reading URL Anchor on IE
I've got a page full of links to another page with anchors on the end (like this: index.html#anchor). On the page they point to, I have a script that is supposed to read where the anchor points to in order to display something.
On firefox it works perfectly, But I've noticed that IE seems to remove t开发者_Python百科he #anchor from the end of the url, so the script can't grab the text. Is there a way around this, without any server side code?
How is it getting the url?
window.location.hash
should contain the contents of the hash.
I've tested the following code in IE 6, 7, and 8, and the correct hash is shown in the alert box in all cases.
<script type="text/javascript">
function showHash() {
var currentUrl = "" + document.location;
var hash = "";
var parts = currentUrl.split("#");
if (parts.length > 1) {
hash = parts[1];
}
alert("the current hash is: " + hash);
}
</script>
<input type="button" value="Show Hash" onclick="javascript: showHash();" />
Does that code work for you?
Does window.location
still contain the anchor on IE, or is it removed there also? If it's still there you could use window.location
and split on the hash:
var whole = "" + window.location; // location is object, make sure it's a String
var parts = whole.split('#');
var anchor = parts[1];
Just try like this
var url = window.location.search.substring(1)
var arr=url.split("#")
str=arr[1]
Here's a function that helps. It returns null if there's no anchor. I placed it inside an Util.js, it comes in handy :D
function getAnchor() {
var currentUrl = document.URL,
urlParts = currentUrl.split('#');
return (urlParts.length > 1) ? urlParts[1] : null;
}
精彩评论