让我们假设以下元素(查找尾随空格和前导空格):
<p>
<span class="item">Lorem Ipsum is simply dummy text </span><span class="item">of the printing and typesetting</span><span class="item"> industry.</span>
</p>
我想用
替换所有空格, 由于 display: inline-block
此处显示的奇怪行为:http://jsfiddle.net/SQuUZ/ (我不知道所有浏览器,但最新的 Chrome 和 Firefox 都一样)。
现在,既然 javascript 是这里的一个选项,jQuery 也是,我可以:
$('p').text($('p').text().replace(/ /g, ' '));
但它转义了
结果变成a mess of entities
.
显然,为此我们可以使用 $('p').html()
:
$('p').html($('p').html().replace(/ /g, ' '));
但是这个更糟,因为它还添加了
在标签本身内:
<p>
<span class="item">Lorem Ipsum is simply dummy text </span><span class="item">of the printing and typesetting</span><span class="item"> industry.</span>
</p>
<!-- TL;DR -->
<span class="item"></span> <!-- is actually invalid... -->
它打破了一切......
注意事项:
- 不会只有
<span>
类item
的元素在容器内(也可能不总是<p>
)。 - 慢速正则表达式是一个选项(问题是,我想不出一个...)。
我在这里有什么选择?
更新:
事实上,谁能解释为什么多行/单行会出现这样的错误 display: inline-block;
? (参见上面的 fiddle 链接,并检查...)
最佳答案
$('p').contents().filter(function(){
return this.nodeType == 3 // Text node
}).each(function(){
this.data = this.data.replace(/ /g, '\u00a0');
});
关于javascript - 用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10474124/