鉴于以下内容:
<div id="bigchuck">
<p>blah blah blah.</p>
<p>yada yada yada.</p>
<p>Tada. Bing bong the witch is dead. Door bell.</p>
</div>
JavaScript / JQUERY如何找到最后一句“门铃”并用标签包装,结果是:
<div id="bigchuck">
<p>blah blah blah.</p>
<p>yada yada yada.</p>
<p>Tada. Bing bong the witch is dead. <span>Door bell.</span></p>
</div>
谢谢
答案 0 :(得分:3)
这个解决方案基于帕特里克的解决方案(他提出了function(i,html)
方法的功劳),但它只包括最后一句而不是它之前的空格:
$('#bigchuck p:last').html( function(i,html) {
var arr = html.split(". ");
arr[arr.length-1]="<span>"+arr[arr.length-1]+"</span>";
return arr.join(". ");
});
答案 1 :(得分:2)
试试这个:
var plast = $("#bigchuck").find("p:last").text();
var part = plast.split("."), pos = part.length - 2;
if (part.length < 2)
pos = 0;
part[pos] = "<span>" + part[pos] + ".</span>";
part.pop(); // <-edit for comment
$("#bigchuck").find("p:last").html(part.join("."));
答案 2 :(得分:2)
试试这个: http://jsfiddle.net/NpjUt/
$('#bigchuck p:last').html( function(i,html) {
var arr = html.split(/(\.)/);
arr.splice(arr.length - 3, 0, '<span>');
arr.push('</span>')
return arr.join('');
});