jquery $(this).id return Undefined

Mah*_*ine 33 asp.net jquery

我在页面上有两个asp单选按钮放在一个updatepanel.我用jQuery为他们写了一个click事件,如下所示:

$(document).ready(function () {
    $(".inputs").click(function () {
         alert($(this).id);
    });
});
Run Code Online (Sandbox Code Playgroud)

但它返回Undefined.问题是什么?

EDIT:

        alert(" or " + $(this).attr("id"));
alert(this.id);
Run Code Online (Sandbox Code Playgroud)

这两行返回null!

Sam*_*son 108

$(this)并且this不一样.第一个表示围绕元素的jQuery对象.第二个是你的元素.该id属性存在于元素上,但不存在于jQuery对象中.因此,您有几个选择:

  1. 直接访问元素上的属性:

    this.id

  2. 从jQuery对象访问它:

    $(this).attr("id")

  3. 从jQuery中拉出对象:

    $(this).get(0).id; // Or $(this)[0].id

  4. idevent对象获取:

    当引发事件时,例如点击事件,它们会携带重要的信息和参考资料.在上面的代码中,您有一个点击事件.此事件对象引用了两个项目:currentTargettarget.

    使用target,您可以获取id引发事件的元素.currentTarget只会告诉你事件当前正在冒泡哪个元素.这些并不总是一样的.

    $("#button").on("click", function(e){ console.log( e.target.id ) });

在所有这些中,最好的选择是直接从this它自己访问它,除非你参与了一系列嵌套事件,那么最好使用event每个嵌套事件的对象(给它们所有唯一的名称)较高或较低范围内的参考元素.

  • 显然这是一个很受欢迎的问题,当我用Google搜索"$(this).id in jquery"时,这是第一搜索结果.你的答案是正确的,并帮助我.我使用.attr()方法,它就像一个魅力.谢谢! (7认同)

Tie*_* T. 36

另一个选择(就是你已经看到它):

$(function () {
    $(".inputs").click(function (e) {
         alert(e.target.id);
    });
});
Run Code Online (Sandbox Code Playgroud)

HTH.


Tat*_*nit 6

Hiya 演示 http://jsfiddle.net/LYTbc/

这是对DOM元素的引用,因此您可以直接将其包装起来.

attrapi:http://api.jquery.com/attr/

.attr()方法仅获取匹配集中第一个元素的属性值.

有个好人,欢呼!

$(document).ready(function () {
    $(".inputs").click(function () {
         alert(this.id);

        alert(" or " + $(this).attr("id"));

    });
Run Code Online (Sandbox Code Playgroud)

});