打印出一个 javascript 变量(没有显示?)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13673553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:26:23  来源:igfitidea点击:

Printing out a javascript variable (not showing up?)

javascriptjquery

提问by Jonathan

I want to make sure a javascript variable is getting the correct values passed into it when setting it to a ruby variable.

我想确保在将 javascript 变量设置为 ruby​​ 变量时,它获得了传递给它的正确值。

<script type="text/javascript" charset="utf-8">

   var test = <%= @test || 'null' %>;
   document.write(test);

</script>

However, there doesn't seem to be any output whatsoever. I've tried just document.write("somethinganything")and I still don't see any output. Is it supposed to appear on webpage or terminal? I couldn't find any in both.

但是,似乎没有任何输出。我已经尝试过了document.write("somethinganything"),但仍然没有看到任何输出。它应该出现在网页或终端上吗?我在两者中都找不到。

回答by dsgriffin

document.writeprints to the webpage. You should try using console.logto print to the terminal.

document.write打印到网页。您应该尝试使用console.log打印到终端。

回答by Steven Moseley

You shouldn't use document.write()to print out visible content unless the script block is in the <body>.

你不应该使用document.write()打印出可见的内容,除非脚本块是在<body>

Some older browsers will not support that, and if the script block is in the <head>it will not write anything visible.

一些较旧的浏览器将不支持该功能,并且如果脚本块在 中<head>,它将不会写入任何可见的内容。

Try one of the following solutions instead:

请尝试以下解决方案之一:

// Append a text node to the end of your body
window.onload = function() {
    var txt = document.createTextNode(test);
    document.body.appendChild(txt); 
};

or

或者

// Log the text to your javascript console
console.log(test);

or

或者

// Alert the text in a popup
window.alert(test);

回答by cruxi

you have to write console.log("test");

你必须写 console.log("test");