Hi,ALL:求助这个奇怪的问题,Demo的代码我贴在下面了,问题是点按钮给表格赋值之后,Alert出来的结果不对,麻烦大家给解决下,顺便讲下原理吧,谢谢!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head><body>
<script language="javascript">
function change()
{
var text='{"tr_1":{"color":"#FF0000"},"tr_2":{"color":"#00FF00"}}';
var json=eval("("+text+")");
for(tr in json)
{
var jcor=json[tr];
var color=jcor['color'];
document.getElementById(tr).style.backgroundColor=color; //到这里都没事儿
document.getElementById(tr).onclick=function(){alert(color)}; //到这里就出问题了
}
}
</script>
<table width="200" border="1">
  <tr id="tr_1">
    <td>&nbsp;</td>
  </tr>
  <tr id="tr_2">
    <td>&nbsp;</td>
  </tr>
</table>
<form action="" method="get" onsubmit='change();return false'>
<input type="submit" value="test" />
</form>
</body>
</html>

解决方案 »

  1.   

    var color=json.color  我记得是这样写的,另外,能不能不要定义变量名为:var json   
    尽量不要用关键字。
      

  2.   

    alert(this.style.backgroundColor)document.getElementById(tr).onclick=function(){alert(this.style.backgroundColor)}; 
      

  3.   

     var color=jcor['color'];jcor???
      

  4.   


    这显然不是解决问题的办法,我要之前没修改this.style.backgroundColor呢?
      

  5.   

        function change() {
            var text='{"tr_1":{"color":"#FF0000"},"tr_2":{"color":"#00FF00"}}';
            var json=eval("("+text+")");
            for(tr in json) {
                var jcor=json[tr];
                var color=jcor['color'];
                document.getElementById(tr).style.backgroundColor=color; //到这里都没事儿
                 document.getElementById(tr).onclick=function(color){
                   return function(){
                     alert(color)
                    }
                 }(color); //到这里就出问题了        }
        }
    你的代码是在for循环后,所以这这里的闭包中的color一直是最后一下变量的值,把每个循环中的实际值传给事件function