簡體   English   中英

jQuery-修剪內部HTML?

[英]Jquery - trim inner HTML?

我以某種方式需要trim()我的內容的innerHTML ...所以我有這樣的東西:

<div>
     <b>test</b>

123 lol
          </div>

我基本上想擺脫僅在<div>和下一個字符之間的空格,以及在結束</div>之前的空格。

因此結果將是:

<div><b>test</b>

123 lol</div>
var $mydiv = $('#mydiv');
$mydiv.html($.trim($mydiv.html());

這應該將內容帶入任何元素,修剪掉元素的空白並將其重置為內容。

我真的不知道為什么要這樣做,但似乎您正在使用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)

您可以輕松編寫一個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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM