给定一个ID,找到最后一个句子并将其替换为跨度包装器 [英] Given an ID, find and replace the last sentence with a span wrapper

查看:82
本文介绍了给定一个ID,找到最后一个句子并将其替换为跨度包装器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下内容:

<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如何找到最后一个句子"Door bell"并用标签将其包裹起来,结果是:

How can JavaScript/JQUERY find the last sentence "Door bell" and wrap it with a tag, to result in:

<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>

谢谢

推荐答案

此解决方案基于patrick的解决方案(他应归功于function(i,html)方法),但它只包装了最后一句话,而不是前面的空格:

This solution is based on patrick's solution (he deserves the credit for coming up with the function(i,html) approach), but it just wraps the last sentence and not the space before it:

$('#bigchuck p:last').html( function(i,html) {
  var arr = html.split(". ");
  arr[arr.length-1]="<span>"+arr[arr.length-1]+"</span>";
  return arr.join(". ");
});

这是行动代码.

这篇关于给定一个ID,找到最后一个句子并将其替换为跨度包装器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆