简体   繁体   English

$(a,this).attr('href')返回undefined

[英]$(a,this).attr('href') returns undefined

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. 当我检查控制台(firebug)它只是说未定义。 please try and help out, as i have tried other methods of getting the data but gets messy. 请尝试帮忙,因为我已经尝试过获取数据的其他方法但是变得混乱。

thanks 谢谢

Seems like .artefact has two a s. 好像.artefact有两个a秒。 Based on this: 基于此:

$('.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);
});

Is .artefact a link? .artefact是链接吗? If yes, why to use $('a', this) instead of just $(this) ? 如果是,为什么要使用$('a', this)而不是$(this)

You have 2 links in the div element (Looking at code you provided). div元素中有2个链接(查看您提供的代码)。 So to get the href (if that link is always the last one in div, you should use: 所以要获得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. 正如其他人所说,你也缺少了肠胃外症。

尝试这个:

var storyId = $(this).attr('href');

你需要使用$(this).attr('href')

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. 您在DIV中有两个锚点,因此您需要指定要选择的锚点。 I used your class name. 我用了你的班级名字。

@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代码也缺少右括号:) );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM