我试图通过在段落和标题内的最后两个单词之间添加不间断空格来防止出现单个单词孤儿。然而,我正在使用的脚本也有删除链接的副作用。
$("p,h1,h2,h3,h4,h5,h6").each(function() {
var wordArray = $(this).text().split(" ");
var finalTitle = "";
for (i=0;i<=wordArray.length-1;i++) {
finalTitle += wordArray[i];
if (i == (wordArray.length-2)) {
finalTitle += " ";
} else {
finalTitle += " ";
}
}
$(this).html(finalTitle);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. <a href="test.php">It has survived</a> not only five centuries, but also the leap into electronic typesetting.</p>
<p> only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software.</p>
尝试使用html()
代替text()
:
$("p,h1,h2,h3,h4,h5,h6").each(function(i,e) {
var text = $(e).html();
text = text.split(' ');
var lastWord = text.pop();
text = text.join(' ') + " " + lastWord;
$(e).html(text);
});
fiddle https://jsfiddle.net/wscourge/owk2dzbe/
顺便说一句,有一种极端情况它不起作用,那就是要非孤立元素的最后一个单词位于<a>
,或任何其他具有属性的标签,例如:
<p>Lorem ipsum dolor sit <a href="">amet.</a></p>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)