【问题标题】:print variable to text area instead of console in javascript将变量打印到文本区域而不是javascript中的控制台
【发布时间】:2021-01-28 01:10:30
【问题描述】:

对此有点困惑。我目前有一些变量在按下按钮时打印到我的控制台,但我希望它们打印到文本区域(在单行上)。

这是我的代码

const freq = palindromes.map(palindrome => ({
  palindrome,
  freq: frequency(palindrome)
}));
console.log('all sentences:', sentences);
console.log('only palindromes:', palindromes);
console.log(freq);
<textarea id="output"></textarea>

刚刚在控制台中显示-

[{
  freq: {
   a: 2,
   c: 2,
   e: 1,
   r: 2
},
  palindrome: "racecar"
}]

我希望它在我在 html 中定义的文本区域内显示为 [{freq: { a: 2, c: 2, e: 1,r: 2}, palindrome: "racecar"}]。我该怎么做呢?

谢谢!

【问题讨论】:

  • 使用JSON.stringify()将数组转换为字符串,然后赋值给textarea的值。

标签: javascript html text


【解决方案1】:
document.getElementById('output').value = JSON.stringify('your variable')

【讨论】:

    【解决方案2】:

    假设我正确解释了您的问题,有很多方法可以实现您正在尝试做的事情。听起来您想要一个文本字段,或者在这种情况下通过使用 textarea 标签来保存一些字符串而不是空的?这可以在启动时完成一次,也可以在运行时通过按钮或其他东西动态完成。所需的代码如下所示:

    <textarea id="output">
    default text.
    </textarea>
    
    <button type="button" onclick="upDateOutput()">Click to update text area</button>
    
    <script>
    function upDateOutput() {
      document.getElementById("output").value = "This is a new string.";
    }
    </script>
    

    【讨论】:

      猜你喜欢
      • 2017-11-18
      • 2011-05-11
      • 2020-09-29
      • 1970-01-01
      • 1970-01-01
      • 2020-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多