2009-01-18 46 views
3

我有我的JScript代码的问题。我试图遍历表中的所有行并添加一个onclick事件。我可以添加onclick事件,但会遇到一些问题。Javascript 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)。

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

回答

3

当在javascript中调用函数时,首先发生的情况是解释器将作用域链设置为函数定义时的状态。在你的情况下,作用域链的样子:

 
    GLOBAL 
    | 
CAll addTableEvents 
    | 
CALL onclick 

所以当变量的orderID是经JavaScript解释器绊倒它搜索该变量的作用域链。没有 orderID定义在您的 onclick函数中,所以下一个看点是 addTableEvents。你可能会认为的orderID在这里被定义,但因为你没有申报的orderID使用var关键字,的orderID成为一个全局变量,所以的orderID没有内部 addTableEvents发现。最后一个要看的地方是在GLOBAL内部,并且它确实存在,它的值是它被分配的最后一个值,在这种情况下,它的最后一个值是 orderID = row.getAttributeNode(“id”)。value ; for循环中的

看到这更清楚地看看下面

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直接从所谓的对象属性。

P.S.我不知道为什么你的代码在IE中不起作用(它在我的IE7中工作)。

+1

谢谢。这很有效,它也帮助我理解这个问题。 – 2009-01-18 06:03:49

2

为什么不将事件处理程序附加到表中,并获取单击处理程序中触发click事件的单元格的rowindex。

-1

y'cant比这更简单!
显然可以与动态构建的行一起使用。
很多爱,
某人。

<html> 

<head> 
<title></title> 
<script language="JavaScript" type="text/javascript"> 
<!-- 
var TO,URL; 
function Link(url){ 
URL=url; 
TO=setTimeout('window.location=URL;',500); 
} 
//--> 
</script> 
</head> 

<body> 

<tr onclick="Link('anotherpage.html');"> 
<td>row1 cell1</td> 
<td>row1 cell2</td> 
</tr> 

<tr onclick="Link('yetanotherpage.html');"> 
<td>row2 cell3</td> 
<td>row2 cell4</td> 
</tr> 

</body> 

</html>