jQuery $(a,this).attr('href') 返回未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5620164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
$(a,this).attr('href') returns undefined
提问by nmyster
Im using ajax to load some data from a mysql database... my problem is, it getting the id for the data i want to load, i have set the HREF value as the id... so an example is:
我使用ajax从mysql数据库加载一些数据......我的问题是,它获取我想要加载的数据的id,我已经将HREF值设置为id......所以一个例子是:
`<a href="16" title="View Story: ssasds">ssasds</a>`,
16 is the id value i need... my code is:
16 是我需要的 id 值...我的代码是:
$('.artefact').click(function()
{
var storyId = $('a',this).attr('href');
console.log(storyId);
}
when i check the console (firebug) it just says undefined. please try and help out, as i have tried other methods of getting the data but gets messy.
当我检查控制台(萤火虫)时,它只是说未定义。请尝试并提供帮助,因为我尝试了其他获取数据的方法但变得混乱。
thanks
谢谢
回答by Salman A
Seems like .artefact
has two a
s. Based on this:
好像.artefact
有两个a
s。基于此:
$('.artefact').click(function () {
var storyId = $('a', this).filter("[href]").attr('href');
console.log(storyId);
});
EDIT
编辑
On second thought, this looks cleaner:
再想一想,这看起来更干净:
$('.artefact').click(function () {
var storyId = $(this).find("a[href]").attr('href');
console.log(storyId);
});
回答by Olegas
Is .artefact
a link? If yes, why to use $('a', this)
instead of just $(this)
?
是.artefact
链接吗?如果是,为什么要使用$('a', this)
而不是仅仅使用$(this)
?
回答by enoyhs
You have 2 links in the div element (Looking at code you provided). So to get the href (if that link is always the last one in div, you should use:
您在 div 元素中有 2 个链接(查看您提供的代码)。因此,要获取 href(如果该链接始终是 div 中的最后一个,则应使用:
$('.artefact').click(function() {
var storyId = $('a', this).last().attr('href');
console.log(storyId);
});
And as others have said, you were missing parentesis too.
正如其他人所说,你也缺少父母。
回答by Deele
Yeah, closing parenthesis is in fault http://jsfiddle.net/h7HuJ/1/I used your given HTML code.
是的,右括号有问题http://jsfiddle.net/h7HuJ/1/我使用了你给定的 HTML 代码。
You have two anchors inside that DIV, so you need to specify, which one to select. I used your class name.
您在该 DIV 中有两个锚点,因此您需要指定要选择哪一个。我用了你的班级名称。
回答by Felix
Try this:
尝试这个:
var storyId = $(this).attr('href');
回答by Andrei Andrushkevich
you need to use $(this).attr('href')
你需要使用 $(this).attr('href')
回答by stealthyninja
@Neil Stewart: See -- http://jsfiddle.net/Chby2/
@Neil Stewart:见——http: //jsfiddle.net/Chby2/
You didn't add the artefact
class to the link and your jQuery code was also missing the closing parenthesis: );
您没有将该artefact
类添加到链接中,并且您的 jQuery 代码也缺少右括号:);