【问题标题】:Jquery - trim inner HTML?Jquery - 修剪内部 HTML?
【发布时间】:2012-01-31 08:12:17
【问题描述】:

我不知何故需要trim()我的内容的innerHTML...所以我有这样的东西:

<div>
     <b>test</b>

123 lol
          </div>

我基本上想去掉仅在&lt;div&gt; 和下一个字符 之间的空白,以及关闭&lt;/div&gt; 之前的空白。

所以结果是:

<div><b>test</b>

123 lol</div>

【问题讨论】:

  • 为什么?这是一种奇怪的需要。
  • @jjj $.trim 不是操作 DOM 的好选择。

标签: javascript jquery regex innerhtml trim


【解决方案1】:
var $mydiv = $('#mydiv');
$mydiv.html($.trim($mydiv.html());

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

【讨论】:

  • 您可以深入 DOM 并找到空白文本节点并手动删除它们。但是 jQuery 在那里帮不上忙,我不知道该怎么做。
  • 没那么难 - 查看element.childNodes,从.firstChild 开始检查.nodeType == 3,如果.textContent 属性全是空格,则删除节点 - 重复直到第一个非文本节点成立。然后从最后一个子节点向后执行。
【解决方案2】:

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

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)

【讨论】:

  • 两个很好的答案,我选择了稍微简洁一点的答案。非常感谢!
  • 实际上它们都不是好的答案 - 正确的方法是显式删除在 div 子列表的开头或结尾找到的空文本节点。不过我现在没时间写。
【解决方案3】:

您可以轻松地编写一个 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-05
    • 2011-01-07
    • 1970-01-01
    • 1970-01-01
    • 2014-11-30
    • 2017-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多