javascript变量赋值

时间:2014-08-11 11:52:18

标签: javascript variables

完全不知道为什么下面的javascript没有按预期分配变量

也许我错过了一些非常简单的事情,因为它持续数小时盯着它!

任何帮助表示感谢。

干杯

var $name;
var $district;
var $distance;
var myArray = [];

jQuery('.getrowdata').on('click', function(){   
  var $row = jQuery(this).closest('tr');
  var $columns = $row.find('td');
  var value;
  jQuery.each($columns, function(i, item){
    value = item.innerHTML;
    if(i < 3){
      myArray.push(value); // adds first 3 elements to the array
    }       
  }
);

$name = myArray[0]; // trying to set value of these variables to value of array element
$district = myArray[1];
$distance = myArray[2];

alert(myArray.join(",  ")); // this works - displays data as expected !!

});

document.write($name);   // these don't work - print out as undefined ?
document.write($district); 
document.write($distance); 

1 个答案:

答案 0 :(得分:3)

变量未定义,因为它们在调用“click”事件处理程序后只有值。

尝试将document.write语句移动到“click”处理程序中:

jQuery('.getrowdata').on('click', function() {

   ...

   document.write($name);
   document.write($district); 
   document.write($distance);
});