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

iKa*_*ars 2 jquery

是否有可能jQuery包含h2标签内的最后一个单词,如果它有多个单词.

例如.

如果h2不做什么

但是,如果h2用括号包裹最后一个字 -h2

amo*_*era 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);   

});
Run Code Online (Sandbox Code Playgroud)

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