如何使用 jquery 设置 pre 标签的文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4973039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to set the text of a pre tag using jquery
提问by Knox
I'm using a pre tag to hold some raw formated text that has carriage returns. When the page is first displayed, it looks fine. Later, I want to refresh just the pre data. I've tried two ways to do this with jquery, one using .html() and the other way with .text(). Both sorta work, but the .html throws away the carriage returns and the .text double spaces the carriage returns! I've also tried .val() but that didn't work at all. Here's the code (of course I only use one of the jquery lines at a time.)
我正在使用 pre 标签来保存一些带有回车符的原始格式化文本。当页面第一次显示时,它看起来不错。后来,我只想刷新预数据。我已经尝试了两种使用 jquery 的方法,一种使用 .html(),另一种使用 .text()。两者都可以工作,但是 .html 丢弃了回车符,而 .text 将回车符加倍了!我也试过 .val() 但这根本不起作用。这是代码(当然,我一次只使用 jquery 行之一。)
<pre id="QComment">Initial Text</pre>
at some time later,
一段时间后,
$('#QComment').text(databack); // or
$('#QComment').html(databack);
回答by Adrian Gonzales
This is a common problem between *nix based systems and windows systems. Someone wrote a simple newline detection plugin for jQuery newlinecharacter
这是基于 *nix 的系统和 windows 系统之间的常见问题。有人为 jQuery newlinecharacter写了一个简单的换行检测插件
So, what you can do is:
所以,你可以做的是:
$('#QComment').text(databack.replace(/\r\n/g,EOL));
Which, what you're doing is replacing all windows style line breaks with ones appropriate for the system viewing the data.
其中,您正在做的是用适合查看数据的系统的换行符替换所有窗口样式的换行符。
回答by Tgr
Works like a charm for me: fiddle demo
对我来说就像一个魅力:小提琴演示
Maybe you have some encoding problem? An example vould help.
也许你有一些编码问题?一个例子会有所帮助。
(.val()
sets the value
attribute on the pre
tag, which of course has no effect.)
(在标签上.val()
设置value
属性pre
,当然没有效果。)
回答by zzzzBov
I would suggest not bothering to use jQuery in this instance, and just set the object using plain old javascript:
我建议不要在这种情况下使用 jQuery,只需使用普通的旧 javascript 设置对象:
document.getElementById('QComment').innerHTML = yourHTML;
There's no reason to add the jQuery overhead to something as simple as this. If you want to use this on multiple elements, jQuery is fine:
没有理由将 jQuery 开销添加到像这样简单的事情上。如果你想在多个元素上使用它,jQuery 很好:
$('#selector, .selector, [selector]').each(function(element, index){
element.innerHTML = yourHTML;
});
回答by Mārti?? Briedis
Try using standard DOM methods, maybe the jQuery does something on it's own:
尝试使用标准的 DOM 方法,也许 jQuery 会自己做一些事情:
$('#QComment')[0].innerHTML = html;