带有表行的 Javascript Onclick

标签 javascript onclick dom-events

我的 JScript 代码有问题。我试图遍历表中的所有行并添加一个 onclick 事件。我可以添加 onclick 事件,但有几个问题。

第一个问题是所有行最终都为 onclick 事件设置了错误的参数。

第二个问题是它只能在 IE 中工作。

代码摘录如下:

shanesObj.addTableEvents = function(){
table = document.getElementById("trackerTable");
for(i=1; i<table.getElementsByTagName("tr").length; i++){
    row = table.getElementsByTagName("tr")[i];
    orderID = row.getAttributeNode("id").value;
    alert("before onclick: " + orderID);
    row.onclick=function(){shanesObj.tableRowEvent(orderID);};
}}

shanesObj.tableRowEvent = function(orderID){
alert(orderID);}

表格位于以下位置...

http://www.blackcanyonsoftware.com/OrderTracker/testAJAX.html

每行的 id 依次是……95、96、94……

由于某些原因,当 shanesObj.tableRowEvent 被调用时,onclick 被设置为所有具有最后一个值 id 在循环中经历迭代的行(94 ).

我在页面中添加了一些警报来说明问题。

最佳答案

当在 javascript 中调用函数时,首先发生的事情是解释器将作用域链设置为函数定义时的状态。在您的情况下,范围链如下所示:

   GLOBAL
     |
CAll addTableEvents 
     |
CALL onclick

So when the variable orderID is stumbled upon by the javascript interpreter it searches the scope chain for that variable. There is no orderID defined inside your onclick function, so the next spot to look is inside addTableEvents. You would think orderID is defined here, but since you did not declare orderID with the var keyword, orderID became a global variable, so orderID is not found inside addTableEvents. The last spot to look is inside GLOBAL, and sure enough it is there, and its value is the last one which it was assigned, and in this case its the last value of orderID = row.getAttributeNode("id").value; in the for loop.

To see this more clearly look at the following

shanesObj.addTableEvents = function(){
table = document.getElementById("trackerTable");
for(i=1; i<table.getElementsByTagName("tr").length; i++){
        row = table.getElementsByTagName("tr")[i];
        orderID = row.getAttributeNode("id").value;
        alert("before onclick: " + orderID);
        row.onclick=function(){var orderID = orderID; shanesObj.tableRowEvent(orderID);};
}
orderID = -1;
}

shanesObj.tableRowEvent = function(orderID){
alert(orderID);
}

点击此处的结果将始终为 -1。

所以,为了解决这个问题,我建议你放弃所有额外的和不需要的代码,并使用类似下面的代码,

for(i=1; i<table.getElementsByTagName("tr").length; i++){
        row = table.getElementsByTagName("tr")[i];
        row.onclick=function(){shanesObj.tableRowEvent(this.id);};

}

只需直接从被调用对象访问 id 属性即可。

附言我不知道为什么您的代码在 IE 中不起作用(它在我的 IE7 中起作用)。

关于带有表行的 Javascript Onclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/454517/

相关文章:

javascript - 使用复制粘贴进行 react 数据网格单元格编辑

javascript - 安装 JQuery 时更改了哪些文件

javascript - 我想在我的 <ul> 菜单中添加一些动态菜单功能。

android - 如何设置android :onClick in xml of a custom view?

javascript - 谷歌地图事件监听器似乎不起作用

javascript - 如何传递 PHP GET URL 变量以使用 Javascript 打开窗口?

javascript - JQuery 验证插件 - 无法验证类

javascript - Ionic 中的 Angularjs $http 发布错误

javascript - 更改类上的元素内部 html?

jquery - 使用 Jquery 检测来自 CKEditor 的 onChange 事件