我正在尝试获取与 jQuery delegate() 函数绑定(bind)的元素的 ID。我想将元素的 ID 传递给另一个函数。返回的 ID 总是“未定义”,我不知道为什么。这是我的代码:
$(document).ready(function() {
var timeout = undefined;
$('body').delegate(
'#tab-form input[type="text"]',
'keypress',
function(){
if(timeout != undefined) {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
timeout = undefined;
alert($(this).attr('id'));
}, 500);
}
);
});
还有我的标记:
<form id="tab-form">
<input type="text" value="" id="Tab_name" name="Tab[name]">
<input type="text" value="" id="Tab_text" name="Tab[text]">
</form>
在文本输入中按下按键会弹出一个 JS 警报,显示“未定义”,而不是像我想象的那样“Tab_name”或“Tab_text”。
我最初的谷歌搜索让我相信 attr('id') 未定义的原因是“this”实际上不是单个 DOM 元素,而是一个数组delegate() 附加到的元素。我无法弄清楚如何访问 jQuery 对象数组中当前绑定(bind)元素的 DOM 对象。
非常感谢任何帮助!
最佳答案
这是因为 this
不是您希望它在匿名函数中的样子,它是 window
。有几种方法可以解决这个问题,例如使用 $.proxy()
,像这样:
timeout = setTimeout($.proxy(function() {
timeout = undefined;
alert(this.id);
}, this), 500);
关于javascript - 在 jQuery live/delegate 中获取 "this"元素 ID,超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3525723/