开发者

jQuery select parent

This might be a duplicate question, however I did search and I got so many different answers that I don't know which to use or how to do this.

<?
if(isset($content))
{
    $i = 1;
    foreach($content as $item)
    {
        echo "<li><a href='#' name='" . $item['id'] . "'>" . $item['title'] . "</a></li>";
        $i++;
    }
}
?>

I've added a function to these links with jQuery to handle an ajax call. I select the lin开发者_高级运维ks as follows:

    $("#tips_list ul li a").click(function(e)   { //... }

However, this doesn't make a lot of sense because now you have to click on the actual text instead of the list item. So I figured I'd re-structure my HTML so the anchor tag wraps around the li tag.

    `<a href="#" name=""><li>foo</li></a>`

I then changed my jQuery code accordingly:

    $("#tips_list ul a li").click(function(e)   { //... }

However, now, when I click.. it grabs the list item tag as $(this); which means I can't really grab the name attribute from the anchor tag. So! What I need to do is to grab the name attribute from the parent anchor tag. And I honestly have no clue what the easiest way to do this is. I'm not that experienced with jQuery.

Thanks a lot for helping me!


Keep the old markup. The later one is quite cranky and use the following script.

$("#tips_list ul li").click(function(e)   {
    var name = $(this).children("a").attr("name");
    alert(name);
}


How about going back to the original method, and set #tips_list ul li a {display:block} in your CSS? That should make the a expand and take up the whole li, making the whole li seem clickable. Your original code should then work fine.


To get the parent of an element you just need to use $(this).parent() So I would do this: $(this).parent('a').attr('name');

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜