开发者

Get part of URL using jquery

I have been googling, a lot, and found quiet many similar issues around the www but not anything that nails my issue to the ground.

I have a jquery function that get the href attribute from an anchor tag, which is supposed to return this value - #SomeIDHere

On my development environment it works perfectly, but on production it returns the current URI + the #ID. I only need the #ID part to make the rest of the script work as intended.

This is how I get the href, now I only need to split the href value and get the #ID part.

function myFunction(sender) {
    var id = sender.getAttribute('href');
    alert(id);
    // functionallity here...
}

I have tried this solution which was a brilliant start but when I tried implementing it I 开发者_如何学JAVAonly got undefined values or javascript errors.

Some of the things I tried:

function myFunction(sender) {
var id = sender.getAttribute('href');
var newID = $(id).search.split('#')[1]; // got an error
alert(id);
// functionallity here...
}

function myFunction(sender) {
var id = sender.getAttribute('href');
var newId = $(id).split('#')[1]; // got an error
// functionallity here...
}

function myFunction(sender) {
var id = sender.getAttribute('href');
var newId = $(sender)[0].search.split('#')[1]; // returned undefined
// functionallity here...
}

Any thought or ideas of how to do this? I'm kind of lost at the moment.


Use jquery

Then see this if this is your need

<a href="a.php#1">1</a>
<a href="a.php#2">2</a>

Jquery Part

$("a").live("click",function(){
   alert($(this).attr("hash"));
});

Working Example On JsFiddle


You've already accepted, but without jQuery you can do this:

var url = 'http://news.ycombinator.com/item?id=2217753#blah';

var index = url.lastIndexOf('#');

var hashId = url.substring(index + 1, url.length);

//alert(hashId);

The variable hashId now contains 'blah';


You are mixing jQuery and JavaScript string functions. This should work (if you can be 100% sure that the URL contains #something):

function myFunction(sender) {
    var id = '#' + sender.getAttribute('href').split('#')[1];
    // or `'#' + sender.href.split('#')[1]`
    // or `'#' + $(sender).attr('href').split('#')[1]`

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜