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

时间:2022-01-13 20:36:25

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);
});

2 个解决方案

#1


To get the id attribute of a field, you would do:

要获取字段的id属性,您可以:

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

To get the text contents of 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, this refers to the element being acted on, so with the code above you would get 'text' or 'textarea' depending on which one you clicked.

请注意点击功能中$(this)的用法。你正在重新使用不能做你想做的选择器。在事件处理程序内部,这指的是被执行的元素,因此使用上面的代码,您将获得“text”或“textarea”,具体取决于您单击的那个。

#2


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,或者在您的示例“text”中。

#1


To get the id attribute of a field, you would do:

要获取字段的id属性,您可以:

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

To get the text contents of 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, this refers to the element being acted on, so with the code above you would get 'text' or 'textarea' depending on which one you clicked.

请注意点击功能中$(this)的用法。你正在重新使用不能做你想做的选择器。在事件处理程序内部,这指的是被执行的元素,因此使用上面的代码,您将获得“text”或“textarea”,具体取决于您单击的那个。

#2


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,或者在您的示例“text”中。