使用jquery获取URL的一部分 [英] Get part of URL using jquery

查看:101
本文介绍了使用jquery获取URL的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在谷歌搜索,发现许多类似的问题围绕着www,但没有任何指导我的问题。

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.

我有一个jquery从锚标记中获取href属性的函数,该标记应该返回此值 - #SomeIDHere

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

在我的开发环境中它完美运行,但在生产时它会返回当前URI + #ID。我只需要#ID部分就可以使脚本的其余部分按预期工作。

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.

这是我获取href的方法,现在我只需要拆分href值并获取#ID部分。

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...
}

我试过这个< a href =https://stackoverflow.com/questions/4059193/jquery-href-anchor-value>解决方案这是一个很好的开始但是当我尝试实现它时,我只得到了未定义的值或javascript错误。

I have tried this solution which was a brilliant start but when I tried implementing it I only got undefined values or javascript errors.

我试过的一些事情:

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.

推荐答案

使用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

Jquery Part

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

JsFiddle上的工作示例

这篇关于使用jquery获取URL的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆