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
How do i get a href value from a link inside li list?
提问by Preston
Here is a Fiddle
这是一个小提琴
I want to get the href
attribute, 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
回答by Blake Plumb
$(this)
is referring to the parent li
of 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 div
should not be in the a
在你的情况下div
不应该在a
回答by bipen
here, $this
is pointing to the <li>
but u need the href
attr of <a>
so find <a>
inside <li>
and get the attr href
...
在这里,$this
指的是<li>
但你需要的href
attr<a>
所以在<a>
里面找到<li>
并得到 attr href
...
try this
尝试这个
$(this).find('a').attr('href');
回答by Sandra Granberg
You want the href
attribute 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 a
instead ?
为什么不在 上设置点击事件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') : '';