如何在jQuery中获取锚标记的ID? [英] How to get the id of an anchor tag in jQuery?

查看:85
本文介绍了如何在jQuery中获取锚标记的ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在jQuery中获取锚标记的ID? 这是标签.

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

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

我需要在一个变量中获取ID,即textarea,text等.

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

我尝试了类似的方法,但是我想没有fieldValue这样的东西.

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

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

推荐答案

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

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

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

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

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

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

请注意点击功能中$(this)的用法.您正在重新使用选择器,该选择器不会执行您想要的操作.在事件处理程序内部,this指的是要执行操作的元素,因此使用上面的代码,您将获得文本"或文本区域",具体取决于您单击的那个元素.

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.

这篇关于如何在jQuery中获取锚标记的ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆