Jquery - 修剪内部HTML?

时间:2012-01-31 08:12:18

标签: javascript jquery regex innerhtml trim

我需要trim()我的内容的innerHTML ...所以我有这样的事情:

<div>
     <b>test</b>

123 lol
          </div>

我基本上想要摆脱只在<div>和下一个字符之间的空白区域,以及在结束</div>之前的空白区域。

结果将是:

<div><b>test</b>

123 lol</div>

3 个答案:

答案 0 :(得分:4)

var $mydiv = $('#mydiv');
$mydiv.html($.trim($mydiv.html());

这应该取内容中的任何元素,从中修剪空格并将其重置为内容。

答案 1 :(得分:1)

我真的不知道你为什么要这样做,但看起来你正在使用jquery,所以你可以使用修剪助手:

var $stuff = $(...the messy html you have above including the outer div);
var tidy = $.trim( $stuff.html() );
// tidy has no more div wrapper so you can do this:
return "<div>" + tidy "</div>"
// or this (but i dunno that it won't pad it again)
$stuff.html(tidy)

答案 2 :(得分:0)

您可以轻松编写一个jQuery插件来执行此操作。我为此创建了静态和实例方法。

您可以切换下面的__DEBUG__TRIM_TYPE变量来更改技巧。每个案例都会产生完全相同的结果。它们是实现相同结果的不同方式。

// jQuery Plugin
// =============================================================================
(function($) {
  $.fn.trimHtml = function() {
    return this.html(function(index, html) {
      return $.trim(html);
    });
  };
  $.trimHtml = function(selector) {
    return $(selector || '*').filter(function() {
      return $(this).data('trim') === true;
    }).trimHtml();
  }
}(jQuery));

// Example
// =============================================================================
$(function() {
  var __DEBUG__TRIM_TYPE = 1; // You can change this to values between 1-3.
  
  switch (__DEBUG__TRIM_TYPE) {
      // Option #1. Select elements by a selector.
      case 1:
        $('.pre-block[data-trim="true"]').trimHtml();
        break;

      // Option #2. Filter elements by a selector and their data.
      case 2:
        $('.pre-block').filter(function() { return $(this).data('trim'); }).trimHtml();
        break;

      // Option #3. Apply function to all elements where the "trim" data is TRUE.
      case 3:
        $.trimHtml();
        break;
  }
});
h1 { font-size: 1.5em; }
.pre-block { display: inline-block; white-space: pre; border: thin solid black; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.js"></script>

<h1>Not Trimmed</h1>
<div class="pre-block" data-trim="false">
  Text not to be trimmed.
  
</div>

<h1>Already Trimmed</h1>
<div class="pre-block" data-trim="false">Text already trimmed.</div>

<h1>Trimmed</h1>
<div class="pre-block" data-trim="true">
  Text that was trimmed.
  
</div>