【问题标题】:In javascript, newline character specified via input does not create a newline in alert在 javascript 中,通过输入指定的换行符不会在警报中创建换行符
【发布时间】:2015-06-12 15:42:44
【问题描述】:

http://jsfiddle.net/bobbyrne01/Lnq5mffs/

HTML ..

<input type="text" id="separator" value="Doesnt\nwork" />
<input type="button" id="button" value="submit" />

javascript ..

document.getElementById('button').onclick = function(){
    alert(document.getElementById('separator').value);
    alert("This\nworks");
};

输出..

  • 第一个对话框:

  • 第二个对话框:

【问题讨论】:

  • 使用文本区域进行多行输入。
  • 尝试在控制台中注销 document.getElementById('separator').value 返回的值
  • @PiX06 这是记录的内容:"Doesnt\nwork"
  • 它被解释为识字字符。如果您确实想输入 \n,则必须在代码中将其替换为真正的回车符,例如jsfiddle.net/Lnq5mffs/1

标签: javascript newline


【解决方案1】:

没错,“\n”只有在字符串字面量中使用时才表示“换行”。您不能指望普通用户会在输入框中输入“\n”,期望它会被解释为新行。当用户在输入框中输入“\n”时,value属性设置为“\\n”。

如果您确实需要将输入框内容解释为字符串文字,则可以使用替换,就像在这个小提琴中:http://jsfiddle.net/Lnq5mffs/2/

document.getElementById('button').onclick = function(){
    alert(document.getElementById('separator').value.replace('\\n', '\n'));
    alert("This\nworks");
};

编辑:如果您想为用户提供输入多行文本的方法,请使用 textarea:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-10
    • 2017-06-13
    • 1970-01-01
    • 1970-01-01
    • 2021-02-24
    相关资源
    最近更新 更多