admin管理员组

文章数量:1323157

I'm using this jQuery selector:

$("a[href*='#']").click(function(e) {
    e.preventDefault();
    alert(#valueinhere)
});

to select links that link to an anchor

My links are absolute and relative so they can look like or like test#anchor or like #anchor

How to get the string #anchor from all links above? Is there any regex or something like that?

(I can't use window.location.hash because of e.preventDefault() that is necessary)

I'm using this jQuery selector:

$("a[href*='#']").click(function(e) {
    e.preventDefault();
    alert(#valueinhere)
});

to select links that link to an anchor

My links are absolute and relative so they can look like http://www.myweb./test#anchor or like test#anchor or like #anchor

How to get the string #anchor from all links above? Is there any regex or something like that?

(I can't use window.location.hash because of e.preventDefault() that is necessary)

Share edited Jan 6, 2014 at 18:01 BenMorel 36.6k51 gold badges205 silver badges336 bronze badges asked Dec 30, 2011 at 19:56 simPodsimPod 13.5k18 gold badges97 silver badges147 bronze badges 4
  • 1 You want to get the hash from the href of the a elements, or from the browser's address bar/location? – David Thomas Commented Dec 30, 2011 at 19:58
  • @David did you read the post? Clearly he wants the hash from the a tag – Eonasdan Commented Dec 30, 2011 at 20:01
  • So why is he even considering window.location.hash? And yes; I did read the question, before asking my own question. – David Thomas Commented Dec 30, 2011 at 20:05
  • I just added window.location.hash info because sometimes there are some people who reply in the way I don't need to – simPod Commented Dec 30, 2011 at 20:09
Add a ment  | 

4 Answers 4

Reset to default 4

Why can't you get the hash from the anchor element?

this.hash

It is independent of whether you're preventing the default behavior of the click event.

$("a[href*='#']").click(function(e) {
    e.preventDefault();
    alert(this.hash);
});

Here's a working example.

$("a[href*='#']").click(function(e) {
    e.preventDefault();
    alert( this.href.split("#")[1] )
});
alert(this.href.split("#")[1]);

Make use of indexOf in String

$('a[href*="#"]').click(function(e) {
    var url = $(this).attr('href');                    
    e.preventDefault();
    var newUrl = url.substring(url.indexOf("#"));
    alert(newUrl);
});

FIDDLE : http://jsfiddle/8SdW2/1/

本文标签: javascriptGet anchor value from absolute url stringStack Overflow