Textarea in IE8 Newline issue

2019-06-24 08:07发布

问题:

I'm making a cross-browser form, which requires a textarea. This textarea receives data by two ways: - Sending an Ajax call to the server and returning data - User inputted data

http://jsfiddle.net/garrettwong/x3KSP/

I'm having an issue on IE8 where the textarea text is not formatted (newlines not being read), where as in Chrome, the same code, nicely formats the textarea. I'm hoping to use a solely JavaScript solution if possible, but I'm not sure where to go from here.

回答1:

Why are you using text()? Set the value using val().

New lines are normally \n\r.



回答2:

Do a replace operation to ensure that there is a \r before every \n:

str = str.replace(/\r?\n/g, "\r\n");

Fiddle

Browsers use \r\n for line breaks, though modern browsers such as Chrome and Firefox can also handle Unix-style \n line breaks. IE8 requires proper \r\n line breaks, which work in all other browsers as well.

And as @epascarello noted, use .val() to manipulate the textarea's value property.



回答3:

Just use "\r\n" for new lines.