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

s

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

据我了解,我知道我们可以id通过使用获取当前元素$(this).attr("id");

但是我并没有接受id它所说的undefined

HTML代码:

<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代码):

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

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

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

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

傻瓜

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

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

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

现在$(this)是指<a>

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章