试图为孤立的单词建立一个小脚本:

Trying to build a little script for orphaned words:

本文关键字:一个 脚本 建立 单词      更新时间:2023-09-26

我想做一个非常简单的脚本来处理一些标题中的孤立词。我以为我写得很好,但是第一个单词被剪掉了。有什么帮助吗?

var buddyUpOrphans = function(element, howMany) {
    $(element).each( function() {
        var $this = $(this);
        var thisText = $this.text().split(' ');
        var wordLength = thisText.length;
        thisText.splice( (wordLength - howMany), 0, '<nobr>');
        thisText.shift('</nobr>');
        thisText = thisText.join(' ');
        $this.html(thisText);
    });
};

CodePen

$(document).ready( function() {
    buddyUpOrphans('p', 2);
    buddyUpOrphans('.test1', 4);
});

.shift方法删除数组的第一个元素(并且不接受任何参数),而看起来您想要在数组的末尾添加一些东西。您可以使用.push方法。

由于您将<nobr></nobr>作为元素添加到数组中,然后执行.join(" "),这确实会产生意想不到的结果,即在它们周围放置空格。

我建议将<nobr></nobr>连接到数组的一些元素的末尾,而不是将它们插入到数组中。

var buddyUpOrphans = function(element, howMany) {
	$(element).each( function() {
		var $this = $(this);
		var thisText = $this.text().split(' ');
		var wordLength = thisText.length;
		thisText[wordLength - howMany - 1] += "<nobr>";
		thisText[wordLength - 1] += '</nobr>';
		thisText = thisText.join(' ');
		$this.html(thisText);
	});
};
$(document).ready( function() {
	buddyUpOrphans('p', 2);
	buddyUpOrphans('.test1', 4);
});
body { 
	color: red;
}
	
nobr {
	color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class='test1'>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eveniet voluptates aperiam cumque, qui error, aliquam velit hic ad sapiente accusamus totam id similique repudiandae doloribus, optio consequatur, voluptatum maiores quod?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsa laudantium rem ut id delectus at eaque inventore rerum, dolorem nisi alias modi asperiores recusandae nulla, iure. Facilis consequatur, impedit ipsa.</p>

因为你使用的是arr.shift();

删除数组的第一个元素并返回该数组。使用arr.push();

添加元素
相关文章: