从 jQuery 中的标签获取值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16647941/
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
Get value from a tag in jQuery
提问by Arun
<a href="?at=privat" at="privat" class="Privat">Privat</a>
I need a Jquery to get the privat from above link. here i Tried .
我需要一个 Jquery 从上面的链接中获取 privat。我在这里试过。
$(".Privat").click(function(e) {
e.preventDefault();
alert($(this).val());
});
but it didn't returns any value? how can i get the value?
但它没有返回任何值?我怎样才能得到价值?
回答by Anthony Grist
The <a>
tag creates an anchor, which doesn't have a value (generally only tags that create inputs do). If you want the value of one of its attributes, then you can use the .attr()
function.
该<a>
标签创建一个锚,它不会有一个值(一般只用于创建输入做标记)。如果您想要其属性之一的值,则可以使用该.attr()
函数。
For example:
例如:
alert($(this).attr('at')); // alerts "privat"
If you want the value of its text (the content between the <a>
and </a>
tags), you can use the .text()
function:
如果你想要它的文本值(<a>
和</a>
标签之间的内容),你可以使用这个.text()
函数:
alert($(this).text()); // alerts "Privat"
If your HTML was a bit different, and your <a>
tag contained other HTML, rather than just text, like this:
如果您的 HTML 有点不同,并且您的<a>
标签包含其他 HTML,而不仅仅是文本,如下所示:
<a href="?at=privat" at="privat" class="Privat"><span>Privat</span></a>
Then you could use the .html()
function to do that (it would return <span>Privat</span>
). The .text()
would still just return "Privat" even though it's wrapped in a span.
然后你可以使用该.html()
函数来做到这一点(它会返回<span>Privat</span>
)。在.text()
仍然只返回“隐私”,即使它包裹在一个跨度。
回答by Nick Andriopoulos
to get the value of an attribute use the appropriate function :
要获取属性的值,请使用适当的函数:
$(this).attr('at');
回答by jasse
Try this :
尝试这个 :
alert($(this).attr('at'));
回答by Ed Hinchliffe
You have privat in many places, but you probably want $(this).html()
which returns the content of the tag.
您在很多地方都有 privat,但您可能想要$(this).html()
返回标签的内容。