2016-12-13 210 views
2

我试图通过在段落和标题中的最后2个单词之间添加一个不间断的空格来防止单个单词孤儿。然而,我正在使用的脚本也有删除链接的副作用。预防孤儿

$("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 += "&nbsp;"; 
 
     } 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>

+0

您的输出看起来像什么 –

回答

3

尝试使用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(' ') + "&nbsp;" + lastWord; 
    $(e).html(text); 
}); 

fiddle

顺便说一下,有一个角落情况下,它不适合工作,这是时要unorphaned元素的最后一个字内<a>或任何其他具有属性的标记,如:

<p>Lorem ipsum dolor sit <a href="">amet.</a></p> 
+0

感谢那份工作。我很高兴链接被排除在外。 –

1

的问题是,你使用.text()它获取的元素的合并文本和它的死者,不死者元素本身,所以当你从生成了一些替代HTML这不包括它们。

您可能必须使用.contents(),以最后text节点,并更换更好的运气与text节点,&nbsp;元素和代表一锤定音一个text节点。