缺少换行符通过JavaScript
问题描述:
访问来自一个选择框(HTML)的选项时,我有以下代码(为了清楚起见清洗码):缺少换行符通过JavaScript
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function updateTextBox()
{
var lstSource = document.getElementById("lstSource");
var details = lstSource[lstSource.selectedIndex].text;
document.getElementById("txtDetails").value = details;
}
</script>
</head>
<body>
<select id="lstSource" onChange="updateTextBox();">
<option value="26">My Text
has a line break!</option>
</select>
<textarea id="txtDetails"></textarea>
</body>
</html>
现在,当我在选择框中单击一个项目我d喜欢在textarea中出现换行符,但是,它们不会显示出来。我在填充选择控件时检查了调试器,并且换行符肯定存在(当我使用具有相同文本的“title”属性时,它们也显示在工具提示中)。当我调试JavaScript代码并查看包含在变量细节中的实际数据(使用charCodeAt)时,我可以看到没有换行符,即“我的文本”和“有换行符”之间没有换行符,只是一个空格字符(代码32)。
有没有人有一个想法,这是可以修复的,还是我必须忍受这种(在我看来)越野车行为?也许我失去了一些东西......
在此先感谢
G.
答
HTML collapses whitespace,包括换行符。
您可以改为使用<br>
元素,但它们的don't work位于<option>
元素内。所以,恐怕你想要达到的是不可能的HTML ...
答
由于HTML折叠空白,包括换行符,你必须在选项列表上另一个 属性,以保留您的文本与空白和换行符
为例:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function updateTextBox()
{
var lstSource = document.getElementById("lstSource");
var details = lstSource[lstSource.selectedIndex].tmpText;
document.getElementById("txtDetails").value = details;
}
function onLoad()
{
var lstSource = document.getElementById("lstSource");
var text = "Test +\n ";
for(var i=0;i<lstSource.options.length;i++)
{
lstSource.options[i].text = text +i;
lstSource.options[i].tmpText = text +i;
}
}
</script>
</head>
<body onload="onLoad()" >
<select id="lstSource" onChange="updateTextBox();">
<option></option>
<option></option>
<option></option>
<option></option>
<option></option>
<option></option>
</select>
<textarea id="txtDetails" ></textarea>
</body>
</html>
谢谢你,至少现在我知道:-) – Gorgsenegger 2010-11-25 13:04:28