萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 判斷元素是否為空:html()、is(':empty')、trim() 三種方案對比與陷阱避坑

三種核心方案對比

方法代碼判斷邏輯注意事項
.html() 取值判斷if (!$('#el').html())內部 HTML 為空字符串含空白字符/換行時為 true,需 .trim()
.is(':empty')$('#el').is(':empty')無子節點(含文本節點)最嚴格:<div> </div> 返回 false
.text().trim()!$('#el').text().trim()可見文本內容為空忽略 HTML 標籤,僅關心文本

陷阱演示

<div id="a"></div>                    <!-- 真空 -->
<div id="b"> </div>                    <!-- 單空格 -->
<div id="c"><!-- 注釋 --></div>           <!-- 只有註釋 -->
<div id="d"><span></span></div>         <!-- 空元素子節點 -->

$('#a').html()        // ""         -> false (空字符串為 falsy)
$('#b').html()        // " "        -> true  (非空字符串為 truthy) ⚠️
$('#b').html().trim() // ""         -> false
$('#a').is(':empty')  // true
$('#b').is(':empty')  // false (有文本節點) ⚠️
$('#c').is(':empty')  // false (註釋算節點) ⚠️
$('#d').is(':empty')  // false (有元素子節點)

推薦通用工具函數

/**
 * 判斷元素是否「視覺上為空」
 * @param {jQuery|Element|string} selector
 * @returns {boolean}
 */
function isVisuallyEmpty($el) {
  $el = $el instanceof $ ? $el : $($el);
  // 1. 無子節點
  if ($el.is(':empty')) return true;
  // 2. 僅包含空白文本節點
  var html = $el.html();
  if (html && !html.trim()) return true;
  // 3. 僅包含不顯示的元素(如 script, style, 隱藏元素)
  var $children = $el.contents().filter(function() {
    return this.nodeType === 1 ? $(this).is(':visible') : this.nodeType === 3 && this.textContent.trim();
  });
  return $children.length === 0;
}

// 使用
if (isVisuallyEmpty('#content')) {
  $('#content').html('

暫無內容

'); }

表單輸入框「值為空」判斷(不同場景)

// input/textarea/select 值為空
$('#input').val() === ''
$('#input').val().trim() === '' // 忽略空白

// 原生
input.value === ''
input.value.trim() === ''

完整驗證頁

<!DOCTYPE html>
<html><head><meta charset="utf-8"><script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script></head><body>
<div id="a"></div>
<div id="b"> </div>
<div id="c"><!-- 註釋 --></div>
<div id="d"><span></span></div>
<div id="e"><span style="display:none">隱藏文本</span></div>
<button onclick="testAll()">測試所有判斷</button>
<pre id="result"></pre>
<script>
function testAll() {
  var cases = ['a','b','c','d','e'];
  var out = '';
  cases.forEach(function(id) {
    var $el = $('#' + id);
    out += '#' + id + ':\n';
    out += '  .html(): "' + $el.html() + '" -> ' + (!$el.html()) + '\n';
    out += '  .html().trim(): "' + $el.html().trim() + '" -> ' + (!$el.html().trim()) + '\n';
    out += '  .is(:empty): ' + $el.is(':empty') + '\n';
    out += '  .text().trim(): "' + $el.text().trim() + '" -> ' + (!$el.text().trim()) + '\n';
    out += '  isVisuallyEmpty: ' + isVisuallyEmpty($el) + '\n\n';
  });
  $('#result').text(out);
}

function isVisuallyEmpty($el) {
  $el = $el instanceof $ ? $el : $($el);
  if ($el.is(':empty')) return true;
  var html = $el.html();
  if (html && !html.trim()) return true;
  var $visible = $el.contents().filter(function() {
    return this.nodeType === 1 ? $(this).is(':visible') : this.nodeType === 3 && this.textContent.trim();
  });
  return $visible.length === 0;
}
</script>
</body></html>

總結建議

  1. 嚴格無子節點:.is(':empty')(CSS :empty 選擇器同邏輯)
  2. 忽略空白文本:.html().trim() === '' 或 .text().trim() === ''
  3. 視覺為空(推薦通用):封裝 isVisuallyEmpty(),處理註釋、隱藏元素、空白文本
  4. 表單值判斷:直接用 .val(),勿用 .html()/.text()
copyright © 萬盛學電腦網 all rights reserved