Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/412.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在div中打印JS对象,使用新行代替\n_Javascript - Fatal编程技术网

Javascript 在div中打印JS对象,使用新行代替\n

Javascript 在div中打印JS对象,使用新行代替\n,javascript,Javascript,我正在一个div中打印一些JS对象。JS对象有一个键,其值是一个带换行符的字符串 字符串 one two three 以div表示的预期值: one two three 我在div里得到了什么 one\ntwo\nthree 代码: const textarea=document.querySelector(“#textarea”); const log=document.querySelector(“#log”); textarea.addEventListener('keypress

我正在一个div中打印一些JS对象。JS对象有一个键,其值是一个带换行符的字符串

字符串

one
two
three
以div表示的预期值:

one
two
three
我在div里得到了什么

one\ntwo\nthree
代码:

const textarea=document.querySelector(“#textarea”);
const log=document.querySelector(“#log”);
textarea.addEventListener('keypress',(事件)=>{
log.innerHTML=JSON.stringify({name:event.target.value});
});

使用转义字符\

{"name":"one\\ntwo\\nthree"}
使用转义字符\

{"name":"one\\ntwo\\nthree"}

JSON中不允许使用换行符
JSON.stringify
永远不会生成带有文字换行符的字符串。使用换行符字符串化某些内容将导致输出字符串包含一个文本反斜杠字符,后跟一个文本
n
字符,这就是您在这里看到的

如果您确实需要
JSON.stringify
,请将其中的所有
\n
替换为实际的换行符

另一个问题是,对于大多数元素,换行符通常不会在呈现的HTML中产生实际的换行。您可以使用




JSON中不允许使用换行符
JSON.stringify
永远不会生成带有文字换行符的字符串。使用换行符字符串化某些内容将导致输出字符串包含一个文本反斜杠字符,后跟一个文本
n
字符,这就是您在这里看到的

如果您确实需要
JSON.stringify
,请将其中的所有
\n
替换为实际的换行符

另一个问题是,对于大多数元素,换行符通常不会在呈现的HTML中产生实际的换行。您可以使用



  • 您必须将
    \n
    替换为

  • 应使用
    keyup
    而不是
    keypress
    否则只能在
    textarea
  • const textarea=document.querySelector(“#textarea”);
    const log=document.querySelector(“#log”);
    textarea.addEventListener('keyup',(事件)=>{
    log.innerHTML=event.target.value.replace(/\n/g,“
    ”) });
    
    
  • 您必须将
    \n
    替换为

  • 应使用
    keyup
    而不是
    keypress
    否则只能在
    textarea
  • const textarea=document.querySelector(“#textarea”);
    const log=document.querySelector(“#log”);
    textarea.addEventListener('keyup',(事件)=>{
    log.innerHTML=event.target.value.replace(/\n/g,“
    ”) });
    只需用keypress替换keypress即可

    const log=document.querySelector(“#log”);
    const textarea=document.querySelector(“#textarea”);
    textarea.addEventListener('keyup',(事件)=>{
    log.innerHTML=JSON.stringify({name:event.target.value.replace(/\n/g,
    )}) });
    
    

    只需用keypress替换keypress即可

    const log=document.querySelector(“#log”);
    const textarea=document.querySelector(“#textarea”);
    textarea.addEventListener('keyup',(事件)=>{
    log.innerHTML=JSON.stringify({name:event.target.value.replace(/\n/g,
    )}) });