不知何故,我需要trim()
我的内容的innerHTML ...所以我有这样的事情:jquery - 修剪内部HTML?
<div>
<b>test</b>
123 lol
</div>
我基本上要摆脱空白,这只是<div>
和下字符之间,和关闭</div>
之前的空白空间。
那么结果将是:
<div><b>test</b>
123 lol</div>
不知何故,我需要trim()
我的内容的innerHTML ...所以我有这样的事情:jquery - 修剪内部HTML?
<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>
为什么?这是一种需要的奇怪的事情。 – 2012-01-31 08:20:43
@jjj'$ .trim'对于操作DOM不是一个好的选择。 – Alnitak 2012-01-31 08:35:49