![](/img/trans.png)
[英]Storing Javascript console.log output to variable and then accessing that variable in html?
[英]How to output javascript variable to the console?
如果我使用以下代码进行计算并将其分配给变量,我将如何在html页面上的任何位置访问该变量? 我认为只是将其声明为result from elsewhere on the page = (quantity * product).toFixed(2) ;
然后允许我使用console.log('result from elsewhere on the page is p * q ' + result);
将其输出到控制台console.log('result from elsewhere on the page is p * q ' + result);
但是当我这样做时,我result from elsewhere on the page is p * q [object HTMLSpanElement]
得到的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]
得到result from elsewhere on the page is p * q [object HTMLSpanElement]
返回。
感谢您对此的任何帮助。
使用window.result
或window["result"]
表示法。
编辑:我以为你没有在其他地方改变result
。
你有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
变量。 确保你没有或给它另一个名字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.