21

如何在 HTML 标签属性中包含换行符?

例如:

<a href="somepage.html" onclick="javascript: foo('This is a multiline string.
This is the part after the newline.')">some link</a>

编辑:对不起,不好的例子,如果标签碰巧不在javascript中,说:

<sometag someattr="This is a multiline string.
This is the part after the newline." />

编辑2:原来字符串中的换行符不是我的问题,它是我调用的javascript函数。FWIW, " &#10;" 可用于 HTML 属性中的换行符。

4

7 回答 7

26

根据我对 HTML 标准的记忆,字符实体在属性中工作,所以这可能有效:

<sometag someattr="This is a multiline string.&#10;This is the part after the newline." />

我不确定您想要的“换行符”是否应该是 (\n) 或 (\r\n),我不确定浏览器是否会按照你想要的方式解释它。

你为什么需要它?您试图通过在 HTML 标记属性中添加换行符来解决什么具体问题?

于 2009-06-11T22:04:41.837 回答
19

要包含多行值,只需在编辑器的下一行继续 html 属性的文本,例如

<input type="submit" value="hallo
hallo"> 

将把第二个大厅放在第一个下面

于 2009-06-11T21:52:44.673 回答
5

作为一般规则,属性中的换行符被保留,因此您的第二个示例可以正常工作。你试过了吗?你能举一个你遇到问题的具体例子吗?

作为测试看看这个: -

<a href="somepage3.html" onclick="javascript: alert(this.getAttribute('thing'))" thing="This is a multiline string.
This is the part after the newline.">some link</a>

警报在属性中包含换行符。

于 2009-06-11T21:49:11.593 回答
1
<a href="somepage.html" onclick="javascript: foo('This is a multiline string. \
This is the part after the newline.')">some link</a>

Javascript 在字符串的新行末尾需要一个反斜杠。

于 2011-12-29T05:42:52.207 回答
0

我不确定,但你可以试试 \r 或 \n

javascript: foo('This is a multiline string.\rThis is the part after the newline.')

或者

javascript: foo('This is a multiline string.\nThis is the part after the newline.')
于 2009-06-11T21:39:18.543 回答
0

通常,HTML 源代码中的换行符会在结果中显示您想要的内容。

(当然取决于编辑器)

于 2009-06-11T21:39:47.497 回答
-2

由于它在 Javascript 中,如果在双引号内,您将使用“\n”(对单引号不肯定,我最近一直在使用 PHP。

老实说,值得一提的是,您应该使用事件和委托器,而不是直接在元素上放置 javascript 事件。

于 2009-06-11T21:41:37.057 回答