如何在 jQuery 中获取锚标记的 id?

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

How to get the id of an anchor tag in jQuery?

jquery

提问by Angeline

How to get the id of an anchor tag in jQuery? This is the tag.

如何在 jQuery 中获取锚标记的 id?这是标签。

 <ul class="formfield">
     <li class="selected"><a href="" id="text">Text</a></li>
     <li><a href="" id="textarea">Textarea</a></li>
 </ul>

I need to get the id, i.e., textarea,text etc in a variable.

我需要在变量中获取 id,即 textarea、text 等。

I tried something like this,but there is no such thing as fieldValue I suppose.

我试过这样的事情,但我想没有 fieldValue 这样的东西。

$('.formfield a').click(function() {         
    fieldType=$('.formfield a').fieldValue();
    alert(fieldType);
});

回答by Paolo Bergantino

To get the idattribute of a field, you would do:

要获取id字段的属性,您可以执行以下操作:

$('ul.formfield a').click(function() {
    var id = $(this).attr('id');
    alert(id);
});

To get the text contentsof the a tags (the text between the opening and closing tags), you would do:

要获取a 标签的文本内容(开始和结束标签之间的文本),您可以执行以下操作:

$('ul.formfield a').click(function() {
    var text = $(this).text();
    alert(text);
});

Please note the usage of $(this)inside the click function. You were re-using the selector which would not do what you want. Inside the event handler, thisrefers to the element being acted on, so with the code above you would get 'text' or 'textarea' depending on which one you clicked.

请注意$(this)点击函数内的用法。您正在重新使用不会做您想要的选择器。在事件处理程序内部,this指的是正在处理的元素,因此使用上面的代码,您将获得 'text' 或 'textarea',具体取决于您单击的那个。

回答by Evgeny

You said you want it in a variable?

你说你想要一个变量?

Here you go:

干得好:

var myvariable = $('ul.formfield a').attr('id');

It will give you the id of the first matched element, or in your example "text".

它将为您提供第一个匹配元素的 id,或者在您的示例中为“文本”。