2

我有以下代码(为了清楚起见,清理了代码):

    <!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>

现在,当我单击选择框中的某个项目时,我希望换行符出现在 textarea 中,但是,它们根本不显示。我在填充选择控件时检查了调试器,并且换行符肯定存在(当我使用具有相同文本的“标题”属性时,它们也显示在工具提示中)。

当我调试 JavaScript 代码并查看变量详细信息中包含的实际数据时(使用 charCodeAt),我可以看到没有换行符,即“我的文本”和“有换行符”之间只有一个空格字符(代码 32)。

有谁知道这是否可以解决,还是我必须忍受这种(在我看来)错误的行为?也许我错过了一些东西......

提前致谢

G。

4

2 回答 2

0

HTML折叠空白,包括换行符。

您可以改用<br>元素,但它们在元素内部不起作用<option>。所以,恐怕你想要实现的目标是 HTML 无法实现的......

于 2010-11-25T12:47:22.147 回答
0

由于 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> 
于 2010-11-25T14:08:05.717 回答