Get part of a URL using jquery

I searched Google many times and found many similar questions around www, but not everything that nailed my problem to the ground.

I have a jquery function that gets the href attribute from a binding tag that should return this value - #SomeIDHere

It works fine in my development environment, but when it is produced, it returns the current URI + #ID. I need only the #ID part for all other scripts to work as intended.

This is how I get href, now all I have to do is split the href value and get the # ID part.

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

I tried this solution , which was a brilliant start, but when I tried to implement it, I only 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...
}

, ? .

+3
3

jquery

,

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

JQuery

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

JsFiddle

+9

, jQuery :

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

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

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

//alert(hashId);

hashId 'blah';

+3

You mix 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]`

}
+1
source

Source: https://habr.com/ru/post/1792175/


All Articles