jquery - jQuery:删除标签但保留内容?
问题描述
我知道以前有人问过这个问题,但我的问题略有不同。
我有一个看起来像这样的 html:
[caption id="attachment_12543" align="aligncentre" width="583"]<img class="wp-image-12543 size-full" src="https://tpc.googlesyndication.com/simgad/11307931562035142140" alt="" width="583" height="400">[/caption]
我需要删除caption
标签并保留其内容(图像和文本)。
我试过这段代码,但它什么也没做。
$("caption").replaceWith(function() { return this.innerHTML; });
$("caption").replaceWith(function() { return this.innerHTML; });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
[caption id="attachment_12543" align="aligncentre" width="583"]<img class="wp-image-12543 size-full" src="https://tpc.googlesyndication.com/simgad/11307931562035142140" alt="" width="583" height="400">[/caption]
有人可以就这个问题提出建议吗?
提前致谢。
解决方案
此版本使用正则表达式仅删除开始和结束标题标签
$('div').html(function(){
var html = this.innerHTML;
html = html.replace(/(\[caption [^\]]+\])/, '');
html = html.replace(/(\[\/caption\])/, '');
return html;
});
img {
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
Other stuff
[caption id="attachment_12543" align="aligncentre" width="583"]
<img class="wp-image-12543 size-full" src="https://tpc.googlesyndication.com/simgad/11307931562035142140" alt="" width="583" height="400">
I got some text yo!!!
[/caption]
Even more stuff
</div>
推荐阅读
- javascript - 如何在 Ruby 中使用 selenium-webdriver/capybara 截取完整的浏览器页面及其元素?
- ruby-on-rails - 如何在单个文件上运行 rdoc 而不会覆盖所有其他文件?
- java - 使用上拉刷新时 Android Studio 中的 ScrollView
- python - 如何在 Python 中将字典拆分为迭代器对象
- asp.net-mvc - TempData 在发布到 Azure 时不起作用
- vba - VBA:将一个集合附加到另一个集合上,例如 VB.NET 中的“.AddRange”
- cassandra - 为什么即使指定了主键,Cassandra 也不允许对没有二级索引的列进行查询/过滤
- macros - 如何为所有数值变量设置缺失值
- docker - Docker:如何获取现有容器的完整容器 ID?
- atom-editor - Atom 编辑器中的 Atom Beautify 包快捷方式/热键不起作用