은 어떻게 든 내가 이런 걸 가지고 ... 내 콘텐츠의 innerHTML을 trim()
해야합니다Jquery - 내부 HTML 트림?
<div>
하고 다음
문자 사이에있는 공백을 제거 할
<div>
<b>test</b>
123 lol
</div>
, 그리고 닫는 직전의 공백은 </div>
입니다.
<div><b>test</b>
123 lol</div>
은 어떻게 든 내가 이런 걸 가지고 ... 내 콘텐츠의 innerHTML을 trim()
해야합니다Jquery - 내부 HTML 트림?
<div>
하고 다음
문자 사이에있는 공백을 제거 할
<div>
<b>test</b>
123 lol
</div>
, 그리고 닫는 직전의 공백은 </div>
입니다.
<div><b>test</b>
123 lol</div>
var $mydiv = $('#mydiv');
$mydiv.html($.trim($mydiv.html());
.
DOM을 순차 나열한 다음 직렬화를 해제하는 것보다 더 좋은 방법이 있어야합니다. – Alnitak
DOM을 뚫고 공백 텍스트 노드를 찾아 수동으로 제거 할 수 있습니다. 그러나 jQuery는 거기서 도움을주지 않을 것이고, 나는 그것을 어떻게하는지 모른다. –
그렇게 힘들지는 않습니다.'.firstChild'에서'.nodeType == 3 '을 확인하고,'.textContent' 속성이 모두 공백 인 경우 노드를 제거하십시오 - 첫 번째 비 텍스트 노드까지 반복하십시오 발견된다. 그런 다음 마지막 하위 노드에서 뒤로 수행하십시오. – Alnitak
당신은이 작업을 수행 할 수 있지만 트림 도우미를 사용할 수 있도록, 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>
왜 ? 그것은 일종의 이상한 일입니다. –
@jjj'$ .trim'은 DOM을 조작하기위한 좋은 옵션이 아닙니다. – Alnitak