php - 如何使用 jQuery 删除 img 周围的 P 标签?

标签 php jquery html

我有一个通过CKEditor输出的网页。我需要它来显示没有 <p></p> 的图像标签,但我需要它将实际文本保留在段落标签内,以便我可以将其定位为样式。

我尝试通过下面的 jQuery 来实现这一点,我在另一篇文章中找到了它,但它对我不起作用..

我已经尝试过:

$('img').unwrap();

我已经尝试过:

$('p > *').unwrap();

这两个都不起作用。我可以从编辑器配置中完全禁用标签,但如果文本没有包含在标签中,我将无法单独定位文本。

输出的 HTML 为:

<body>
<div id="container" class="container">
<p><img alt="" src="http://localhost/integrated/uploads/images/roast-dinner-main-xlarge%281%29.jpg" style="height:300px; width:400px" /></p><p>Our roast dinners are buy one get one free!</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('p > *').unwrap();
});
</script>
</body>

感谢所有帮助!

最佳答案

通常使用完成

$('img').unwrap("p");

但这也会从 <p> 中孤立任何其他内容(如文本)。父级(包含图像的)。

所以基本上你想将图像移出 <p>标签。
您可以将图像移动到两个位置:p之前之后标签:

$("p:has(img)").before(function() { // or use .after()
  return $(this).find("img");
});
p {
  background: red;
  padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div id="container" class="container">
  <p>
    <img alt="" src="http://placehold.it/50x50/f0b" />
  </p>
  <p>
    Our roast dinners are buy one get one free!
  </p>
</div>

<p>
  <img src="http://placehold.it/50x50/f0b" alt="">
  Lorem ipsum dolor ay ay
  <img src="http://placehold.it/50x50/0bf" alt="">
</p>

<p>
  <img src="http://placehold.it/50x50/0bf" alt="">
</p>

尽管请注意,上面的内容不会删除空的 <p>我们留下的标签。 See here how to remove empty p tags

补救措施

如果您想删除空段落 - 如果图像是唯一的子元素 -
并保留同时包含图像和其他内容的段落:

$("p:has(img)").each(function() {
    $(this).before( $(this).find("img") );
    if(!$.trim(this.innerHTML).length) $(this).remove();
});
p{
  background:red;
  padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="container" class="container">
  <p>
    <img alt="" src="http://placehold.it/50x50/f0b" />
  </p>
  <p>
    Our roast dinners are buy one get one free!
  </p>
</div>

<p>
  <img src="http://placehold.it/50x50/f0b" alt="">
  Lorem ipsum dolor ay ay
  <img src="http://placehold.it/50x50/0bf" alt="">
</p>

<p>
  <img src="http://placehold.it/50x50/0bf" alt="">
</p>

关于php - 如何使用 jQuery 删除 img 周围的 P 标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43204996/

相关文章:

php - 在 openlayers 3 中单击标记时显示弹出窗口

php从sql数据库读取数据

javascript - 人力车通过自定义按钮删除系列(切换操作)

jquery - 实现 CSS 过渡

javascript - 复制动态元素大小

javascript - jQuery 的 Form Data() 和 Ajax 导致文件提交失败

php - CakePHP 多对一 - 单表

php - 在 PHP 数组中设置值

jquery - 如何查找具有特定属性及其值的标签

html - 响应式网站无法联机使用,但在本地计算机上保存并打开时可以使用。为什么?