在 javascript 中,通过输入指定的换行符不会在警报中创建换行符

In javascript, newline character specified via input does not create a newline in alert

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");
};

输出..

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

如果你确实需要将输入框内容解释为字符串字面量,你可以使用replace,像这样fiddle:http://jsfiddle.net/Lnq5mffs/2/.

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

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