从 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

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

Get value from a tag in jQuery

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()返回标签的内容。

回答by pala?н

The .val()method is primarily used to get the values of form elements such as input, selectand textarea. Try this for getting the link text:

.val()方法主要用于获取input,select和等表单元素的值textarea。试试这个来获取链接文本:

alert($(this).text());

FIDDLE DEMO

小提琴演示