我在页面上有两个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对象中.因此,您有几个选择:
直接访问元素上的属性:
this.id
从jQuery对象访问它:
$(this).attr("id")
从jQuery中拉出对象:
$(this).get(0).id; // Or $(this)[0].id
id从event对象获取:
当引发事件时,例如点击事件,它们会携带重要的信息和参考资料.在上面的代码中,您有一个点击事件.此事件对象引用了两个项目:currentTarget和target.
使用target,您可以获取id引发事件的元素.currentTarget只会告诉你事件当前正在冒泡哪个元素.这些并不总是一样的.
$("#button").on("click", function(e){ console.log( e.target.id ) });
在所有这些中,最好的选择是直接从this它自己访问它,除非你参与了一系列嵌套事件,那么最好使用event每个嵌套事件的对象(给它们所有唯一的名称)较高或较低范围内的参考元素.
Tie*_* T. 36
另一个选择(就是你已经看到它):
$(function () {
$(".inputs").click(function (e) {
alert(e.target.id);
});
});
Run Code Online (Sandbox Code Playgroud)
HTH.
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)
});