1

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

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

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

</script>

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

4

3 回答 3

6

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

于 2012-12-02T20:34:22.780 回答
3

除非document.write()脚本块位于<body>.

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

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

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

或者

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

或者

// Alert the text in a popup
window.alert(test);
于 2012-12-02T20:34:54.793 回答
1

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

于 2012-12-02T20:34:29.917 回答