如何在jQuery中获取元素的id?

时间:2014-08-06 13:16:40

标签: javascript jquery

我是jQuery的新手,我目前正在尝试获取已在页面中点击的元素的id

据我所知,我知道我们可以使用id

获取$(this).attr("id");当前元素

但我并没有接受id,而是说undefined

HTML code:

<html>
    <body>
        <form action="#">
            <a href='#' id="1st">First</a></br>
            <a href='#' id="2nd">Second</a></br>
            <p id='3rd'>Test text</p>
        </form>
        <script type="text/javascript" src="jquery.js"> </script>
        <script type="text/javascript" src="code.js"> </script>
    </body>
</html>

code.js(jQuery code):

$(document).click(function(){
    alert($(this).attr("id"));
    });

以下代码如何完美地返回id:

$(document).click(function(event){
    alert(event.target.id);
    });

有人可以解释为什么会这样吗?我误解了什么?感谢。

3 个答案:

答案 0 :(得分:1)

正如Jason P在评论中指出的那样,您将.click()事件绑定到$(document),因此对$(this)的所有引用都将引用$(document) 。由于您要求$(document) ID ,您将收到未定义的错误,因为没有 ID

如果您尝试获取<a> ID ,那么您需要将.click()事件绑定到该事件,例如:

$("a").click(function(){
     alert( $(this).attr("id") );
});

$(this)现在指的是<a>

请注意,我们会将.click()事件附加到每个 <a>

答案 1 :(得分:1)

这是因为$(this)指的是文档(事件绑定的内容)。回调中的event.target参数指的是被单击的元素。

如果要与.attr()结合使用,可以将event.target包装到jquery对象并调用attr('id')

 $(document).click(function(event){
    alert($(event.target).attr("id"));
 });

参见jsfiddle:http://jsfiddle.net/85HK4/1/

PS:你在这里看到的与事件冒泡有关。请参阅:http://www.quirksmode.org/js/events_order.htmlWhat is event bubbling and capturing?

简而言之:event.target指的是您点击的元素,这是指您将event绑定到的元素。

答案 2 :(得分:1)

<script>
$(document).ready(function() {

   $(".well").mouseenter(function(e) {
        alert($(this).attr("id"));
    });

  });

</script>

<div class="container">
<h2 class="text-info"> Check</h2>
        <div class="well" id="first">
            <a href='#' id="1st" class="text-warning">First</a></br>
            <a href='#' id="2nd">Second</a></br>
        </div>
</div>

这里$ this指的是任何事件,例如,mouseenter,click,mouseup等绑定到某个dom元素,您可以使用任何类,id或任何属性进行选择。

和$ this绑定事件,dom撤销被调用的请求。这里是带有类的id dom元素:'well'

现在,如果你包括,第二个div与同一个类。像

<div class="well" id="second">
            <a href='#' id="1st" class="text-warning">First</a></br>
            <a href='#' id="2nd">Second</a></br>
</div>

每个班级都会用它的dom检查发生的事件。因此,事件和选择器都应匹配以提供所需的结果,$ this将两者绑定并相应地读取以得到结果。

在第二种情况下,当您将鼠标悬停在第二个div上时,它将提示第二个。