Jquery 如果H2有多个单词,则将最后一个单词用span换行

Jquery 如果H2有多个单词,则将最后一个单词用span换行,jquery,Jquery,如果jQuery包含多个单词,是否可以将最后一个单词包装在h2标记中 比如说 如果: 示例 总比什么都不做好 但如果: <h2>This is next example</h2> 这是下一个示例 而不是把最后一个单词用空格括起来 <h2>This is next <span>example</span></h2> 这是下一个示例 您应该能够执行以下操作: $("h2").each(function () {

如果jQuery包含多个单词,是否可以将最后一个单词包装在
h2
标记中

比如说

如果:

示例
总比什么都不做好

但如果:

<h2>This is next example</h2>
这是下一个示例
而不是把最后一个单词用空格括起来

<h2>This is next <span>example</span></h2>
这是下一个示例

您应该能够执行以下操作:

$("h2").each(function () {
    var html = $(this).html();
    var split = html.split(" ");
    if (split.length > 1) {
        split[split.length - 1] = "<span>" + split[split.length - 1] + "</span>"
        $(this).html(split.join(" "));
    }
});
$(“h2”)。每个(函数(){
var html=$(this.html();
var split=html.split(“”);
如果(拆分长度>1){
split[split.length-1]=“”+split[split.length-1]+“”
$(this.html(split.join(“”));
}
});
通过将其拆分,您可以检查是否有多个单词,然后调整最后一个要包装在span中的单词。

$(“h2”).html(function(){
$("h2").html(function(){

  // separate the text by spaces
  var text= $(this).text().split(" ");

  // drop the last word and store it in a variable
  var last = text.pop();

  // join the text back and if it has more than 1 word add the span tag
  // to the last word
  return text.join(" ") + (text.length > 0 ? " <span>"+last+"</span>" : last);   

});
//用空格分隔文本 var text=$(this.text().split(“”); //删除最后一个单词并将其存储在变量中 var last=text.pop(); //将文本连接回来,如果它有超过1个单词,则添加span标记 //最后一句话 返回text.join(“”+(text.length>0?“+last+”:last); });
请参见演示:

$("h2").html(function(){

  // separate the text by spaces
  var text= $(this).text().split(" ");

  // drop the last word and store it in a variable
  var last = text.pop();

  // join the text back and if it has more than 1 word add the span tag
  // to the last word
  return text.join(" ") + (text.length > 0 ? " <span>"+last+"</span>" : last);   

});