hip*_*ail 13 html jquery whitespace line-breaks
从jQuery选择中获取文本是微不足道的:
<span id="foo">hello world</span>
$('#foo').text();
Run Code Online (Sandbox Code Playgroud)
hello world
但是当jQuery选择包含<br>标签时,它们在概念上是新行,它们是空格.不幸的是.text()完全剥离它们
<span id="foo">hello<br>world</span>
$('#foo').text();
Run Code Online (Sandbox Code Playgroud)
helloworld
如何从这样的跨度中提取文本,从而产生hello world相反的结果呢?
当然,这是为了使问题清楚而发明的一个简单的例子.一个真正的答案需要"等同于.text()"并处理任意HTML.这是一个稍微棘手的例子,也是:
<div id="foo"><span class="bar"><em>hello</em><br></span>world</div>
Run Code Online (Sandbox Code Playgroud)
Sus*_* -- 12
用 .html()而不是.text()
$('#foo').html();
Run Code Online (Sandbox Code Playgroud)
或者使用DOM方法 .innerText
$('#foo')[0].innerText ;
Run Code Online (Sandbox Code Playgroud)
Mus*_*usa 11
由于Mims建议使用replaceWith()更改<br>为空格,但不改变原始元素用于clone()复制元素.
var foo = $("#foo").clone();
foo.find("br").replaceWith(" ");
var text = foo.text();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6737 次 |
| 最近记录: |