jQuery 如何从 li 列表中的链接获取 href 值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14175361/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:19:23  来源:igfitidea点击:

How do i get a href value from a link inside li list?

jquery

提问by Preston

Here is a Fiddle

这是一个小提琴

I want to get the hrefattribute, I use $(this).attr('href')but it does not work!

我想获取href属性,我使用$(this).attr('href')但它不起作用!

HTML:

HTML:

<div class="wrap_atletas_interno">
    <ul>
        <li class="atleta">
            <a href="teste.html">
                <div class="nome_86_atleta">Ant?nio</div>
                <img src="atletas/antonio_86px.jpg" />
            </a>
        </li>
        <li  class="atleta">
            <div class="nome_86_atleta">Cauê</div>
            <img src="atletas/caue_86px.jpg" />
        </li>
        <li class="atleta">
            <div class="nome_86_atleta">Dudu</div>
            <img src="atletas/dudu_86px.jpg" />
        </li>
    </ul>
</div>

JavaScript:

JavaScript:

$('.atleta').click(function (e) {
    e.preventDefault();
    $('.atleta').removeClass('atleta_atual');
    $(this).addClass('atleta_atual');
    var h = $(this).attr('href');
    alert(h);
    $.get(h, function (data) {
        //$(".detalhes_atleta").html(data).fadeIn("slow");
        alert(h);
    });
});

回答by Akhil Thayyil

Check the updated fiddle

检查更新的小提琴

Changed

改变了

var h = $("a",this).attr('href');

回答by Blake Plumb

$(this)is referring to the parent liof the link. You need to use

$(this)li的是链接的父级。你需要使用

$(this).find('a').attr('href');

Also please fix your html, block elements should not be inside inline elements.

另外请修复您的html, 块元素不应在内联元素内。

In your case the divshould not be in the a

在你的情况下div不应该在a

回答by bipen

here, $thisis pointing to the <li>but u need the hrefattr of <a>so find <a>inside <li>and get the attr href...

在这里,$this指的是<li>但你需要的hrefattr<a>所以在<a>里面找到<li>并得到 attr href...

try this

尝试这个

$(this).find('a').attr('href');

回答by Sandra Granberg

You want the hrefattribute from a, but $(this)in your example is for the li, that is why it is not working.

您想要href来自的属性a,但$(this)在您的示例中用于li,这就是它不起作用的原因。

Why not set the click event on the ainstead ?

为什么不在 上设置点击事件a呢?

Example: $('.atleta a').click(function(e) ...

例子: $('.atleta a').click(function(e) ...

回答by Scott Evernden

try

尝试

var h = $('a', this).attr('href');

回答by Rafay

try this instead

试试这个

     var href= $('a',this).length>0? $('a',this).attr('href') : '';