我试图通过在段落和标题的最后两个单词之间添加一个不间断的空格来防止单个单词孤立。但是,我使用的脚本也具有删除链接的副作用。
$("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
顺便说一句,在某种情况下它是行不通的,这是当元素的最后一个单词要孤立的是在
<a>
或任何其他具有属性的标签内时,例如:<p>Lorem ipsum dolor sit <a href="">amet.</a></p>
关于javascript - 预防孤儿,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41122565/