如何删除图像标记之间的换行符

时间:2016-07-17 14:49:22

标签: jquery

我试图找出如何删除图像标记之间和之后的换行符,但保留其他任何内容(使用jQuery)。例如:

<p>
   some text
   <br>
   more text
</p>
<br>
<img src="image.jpg" alt="image">
<br>
<br>
<img src="image2.jpg" alt="image">
<br>
<img src="image3.jpg" alt="image">
<br>

会变成:

<p>
   some text
   <br>
   more text
</p>
<br>
<img src="image.jpg" alt="image">
<img src="image2.jpg" alt="image">
<img src="image3.jpg" alt="image">

任何想法都会非常感激。

3 个答案:

答案 0 :(得分:4)

我建议,对于发布的代码:

&#13;
&#13;
// select all <img> elements:
$('img')
  // select all sibling elements of
  // the <img> elements that match the
  // supplied ('br') selector:
  .siblings('br')
  // remove those found siblings:
  .remove();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
  some text
  <br>more text
</p>
<br>
<img src="image.jpg" alt="image">
<br>
<br>
<img src="image2.jpg" alt="image">
<br>
<img src="image3.jpg" alt="image">
<br>
&#13;
&#13;
&#13;

对于稍微复杂的案例(以及此案例),以下可能是首选:

&#13;
&#13;
// select all <img> elements:
$('img')
  // get all subsequent siblings until an element
  // is found which matches the supplied selector
  // (':not(br)'), in this case the selector matches
  // any element that is not a <br> element:
  .nextUntil(':not(br)')
  // we remove those elements that are found
  // which must be <br> elements, given the
  // above selector:
  .remove();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
some text
<br>more text
<br>
<img src="image.jpg" alt="image">
<br>
<br>
<img src="image2.jpg" alt="image">
<br>
<img src="image3.jpg" alt="image">
<br>
&#13;
&#13;
&#13;

参考文献:

答案 1 :(得分:1)

$('img + br').remove(); try this

答案 2 :(得分:0)

删除图片之间的所有<br>标记。

$(document).ready(function(){

  $("img").nextUntil('img').remove();

});

<p>
  some text
  <br>
  more text
</p>
<br>
<img src="image.jpg" alt="image">
<br>
<br>
<img src="image2.jpg" alt="image">
<br>
<img src="image3.jpg" alt="image">