如何将javascript变量输出到控制台?

时间:2013-12-17 12:14:35

标签: javascript

如果我使用以下代码进行计算并将其分配给变量,我将如何在html页面的任何位置访问该变量?我认为简单地将其声明为result from elsewhere on the page = (quantity * product).toFixed(2) ;然后允许我使用console.log('result from elsewhere on the page is p * q ' + result); 将其输出到控制台但是当我这样做时,我得到result from elsewhere on the page is p * q [object HTMLSpanElement]作为输出

<script>
$('#quantity,#product').bind('change keyup', function () {
  var product = $('#product').val(),
      quantity = parseInt($('#quantity').val(), 10),
      result = (quantity * product).toFixed(2);
  $('#result').text(result);
  console.log('Testing console');
  console.log('result is p * q ' + result);
  console.log('quantity is ' + quantity);
});

</script>   

注意:第一个输出console.log('result is p * q ' + result); 工作正常并输出result is p * q 98.00只有当我从外面尝试它时才会返回result from elsewhere on the page is p * q [object HTMLSpanElement]

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

使用window.resultwindow["result"]符号。

编辑:我认为你没有在其他地方更改result

答案 1 :(得分:1)

你有result的变量声明。

var ...., result = (quantity * product).toFixed(2);

当您声明一个变量时,它会在当前函数的范围内声明(如果在所有函数之外执行它,则为全局范围)。

相反,在外部范围内声明它并使用它:

var result;
$('#quantity,#product').bind('change keyup', function () {
  var product = $('#product').val(),
      quantity = parseInt($('#quantity').val(), 10);

  result = (quantity * product).toFixed(2);
  $('#result').text(result);
  console.log('Testing console');
  console.log('result is p * q ' + result);
  console.log('quantity is ' + quantity);
});
//result is now available here, 
// (but equal to undefined until someone will trigger the event)

请注意,由于您获得“来自页面上其他位置的结果是p * q [object HTMLSpanElement]”,您可能已在该范围内拥有 result变量。确保你没有或给它另一个名字。