简体   繁体   中英

$(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:

`<a href="16" title="View Story: ssasds">ssasds</a>`,

16 is the id value i need... my code is:

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

Seems like .artefact has two a s. 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? If yes, why to use $('a', this) instead of just $(this) ?

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:

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

You have two anchors inside that DIV, so you need to specify, which one to select. I used your class name.

@Neil Stewart: See -- http://jsfiddle.net/Chby2/

You didn't add the artefact class to the link and your jQuery code was also missing the closing parenthesis: );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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