下面的示例演示了这个问题:
$("#ex1").append("\r"); //This one works as expected
$("#ex2").append("\n"); //This also works as expected
$("#ex3").append("\r\n"); //This also works as expected
$("#ex4").append("\r <el></el>"); //This replaces \r with \n
$("#ex5").append("\r\n <el></el>"); //This removes \r completely
$("div").on("click", function() {
alert(JSON.stringify(this.innerHTML));
});
<!-- Note: this also works in the JQuery 2.0 branch -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Click the divs below to see the result.
<div id="ex1">R: </div>
<div id="ex2">N: </div>
<div id="ex3">RN: </div>
<div id="ex4">R + El: </div>
<div id="ex5">RN + El: </div>
为什么jQuery的append的回车输出不一致?
直接使用DOM,附加文本节点等,保留
\r
(至少在Chrome和Linux上):document.getElementById("ex1").appendChild(document.createTextNode("\r"));
document.getElementById("ex2").appendChild(document.createTextNode("\n"));
document.getElementById("ex3").appendChild(document.createTextNode("\r\n"));
document.getElementById("ex4").appendChild(document.createTextNode("\r "));
document.getElementById("ex4").appendChild(document.createElement('el'));
document.getElementById("ex5").appendChild(document.createTextNode("\r\n "));
document.getElementById("ex5").appendChild(document.createElement('el'));
document.addEventListener("click", function(e) {
if (/^ex\d$/.test(e.target.id)) {
alert(JSON.stringify(e.target.innerHTML));
}
}, false);
<!-- Note: this also works in the JQuery 2.0 branch -->
Click the divs below to see the result.
<div id="ex1">R: </div>
<div id="ex2">N: </div>
<div id="ex3">RN: </div>
<div id="ex4">R + El: </div>
<div id="ex5">RN + El: </div>
最佳答案
http://jsfiddle.net/19gc7pjt/3/
这不是jQuery的问题。
我认为这是与javascript相关的浏览器问题。
(即IE使用“\r”,其他使用“\n”。我在Chrome上测试过btw ...)
您可以在警报窗口中看到完全相同的结果。
'\r'被忽略。
$("#ex1").append("\r"); //This one works as expected
$("#ex2").append("\n"); //This also works as expected
$("#ex3").append("\r\n"); //This also works as expected
$("#ex4").append("\r <el></el>"); //This replaces \r with \n
$("#ex5").append("\r\n <el></el>"); //This removes \r completely
var text4 = "\r <el></el>";
var text5 = "\r\n <el></el>";
alert(text4); //check this
alert(text5); //and this
$("div").on("click", function () {
alert(JSON.stringify(this.innerHTML));
});