如果H2有多个单词,则用span包裹最后一个单词

时间:2011-08-24 07:11:25

标签: jquery

如果jQuery包含多个单词,那么jQuery是否可以在h2标记内包装最后一个单词。

例如。

如果:

<h2>Example</h2>

比什么都不做

但是如果:

<h2>This is next example</h2>

而不是用span包裹最后一个单词。

<h2>This is next <span>example</span></h2>

2 个答案:

答案 0 :(得分:8)

$("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);   

});

参见演示: http://jsfiddle.net/VHDpT/1/

答案 1 :(得分:1)

您应该能够做到这样的事情:

$("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(" "));
    }
});

通过拆分它,您可以检查是否有多个单词,然后调整最后一个单词以包裹在一个单位中。

相关问题