jquery - 使用 <p> 将特定元素后的文本换行

标签 jquery html css

我有一些这样的 HTML:

<div class="text">
    <img src="http://placehold.it/50x50"/><a href="http://www.example.com" class="ht">the link</a>
    this element doesn't look right, the text displays next to the link
</div>
<div class="text">
    <img src="http://placehold.it/50x50"/><a href="http://www.example.com" class="ht">the link</a> 
    <p>this is a proper kind of element, i want them wrapped in paragraphs or at least looking like they've been wrapped in paragraphs</p>
</div>

我想知道是否可以从第一个示例中制作文本 <div>显示在链接下方,就像包装 <p></p>围绕文本,使用 jQuery。不可能更改 HTML,因为它是用户生成的评论类型的元素,我不能完全强制用户输入 <p></p>围绕他们的文字。他们中的大多数人都这样做,但有些人不这样做,所以我需要找到一种解决方案,使他们都显示相同。

我做了一些研究并找到了这个答案:Selecting text only following certain elements using javascript/jquery 但它并没有真正回答我的问题,因为它基于特定的固定文本结构,而我所拥有的文本实际上可以是用户输入的任何内容,我需要它显示在图像和链接下方,它们显示在同一个线。此解决方案:Wrap text after particular symbol with jQuery对我也不起作用,因为没有可用于识别展开文本的设置 HTML。这个:Find text in element that is NOT wrapped in html tags and wrap it with <p>也没有做我需要的,因为有时我们有人使用 <b></b><i></i>

我尝试过的其他事情:

  • 使图片和链接有display:block;float:left;哪个 不起作用,因为文本仍然显示在与 图片和链接
  • 使图片和链接有display:block;没有 float - 不起作用,因为图像和链接不显示在同一个 行了
  • 使用 $("a.ht").next()选择,这是行不通的

所以如果有人能帮我解决这个问题,我将不胜感激,谢谢!

编辑:这是我想要的示例:

最佳答案

尝试类似的东西:

$('.text').each(function() {
  var el = $(this).clone().find('img,.ht');//get the image and the title 
  var text = el.remove().end().html();//remove the elements, get the remaining html
  $(this).html(el).append('<p>' + text + '</p>');//add the p with the remaining html

});
p {color:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text">
  <img src="http://placehold.it/50x50" /><a href="http://www.example.com" class="ht">the link</a>
  this element doesn't look right, the text displays next to the link
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text">
  <img src="http://placehold.it/50x50" /><a href="http://www.example.com" class="ht">the link</a>
  this element doesn't look right, the <b>text displays next</b> to the <i>link</i>
</div>

关于jquery - 使用 <p> 将特定元素后的文本换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40486362/

相关文章:

javascript - 模式隐藏时滚动条未恢复

jquery - 如何在他们的 click jquery 上交换两个链接

javascript - 由于 Css Transition,点击未完成

javascript - 日期和 Html 值

javascript - 无法POST表单数据

JavaScript/JQuery 改变滚动背景

javascript - 在 jquery 中创建命名空间时出错

javascript - 如何用一个函数创建多个 jquery 函数?

javascript - CSS 框阴影重叠

javascript - 如何将动态样式属性设置为对象属性