【问题标题】:Issue with Javascript Event Handler using a variable outside its scopeJavascript事件处理程序使用其范围之外的变量出现问题
【发布时间】:2013-06-13 04:03:27
【问题描述】:

我有一个这样的 javascript 事件处理程序:

for (i = 0; i < x; i++){
 var table = tableList[i];
 var tableID = table.getAttribute('id');

 var selector = table.querySelectorAll('input')[0];
 selector.on('focusout', function(){
    alert(tableID);
 }):
}

tableID 警报始终是 tableList 中最后一个表的 ID,无论我使用的是哪个表。

有什么想法吗?

【问题讨论】:

  • 您是否将相同的id 应用于多个元素?
  • 为什么是table.querySelectorAll("input")[0] 而不是table.querySelector("input")?此外,selector 似乎是一个用于引用元素的奇怪变量名。而table.getAttribute("id") 可以是table.id;

标签: javascript jquery scope asp.net-web-api


【解决方案1】:

您可以将 tableID 作为数据对象附加到您的事件处理程序。请尝试以下操作。

selector.on('focusout', { tableID: tableID }, function(e) {
    alert(e.data.tableID);
}):

根据 jQuery 文档。

//data
//Type: Anything
//Data to be passed to the handler in event.data when an event is triggered.

【讨论】:

    猜你喜欢
    • 2011-10-23
    • 2018-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-14
    • 2022-11-19
    • 2016-01-05
    • 2017-05-04
    相关资源
    最近更新 更多