| 方法 | 代碼 | 判斷邏輯 | 注意事項 |
|---|---|---|---|
.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>
.is(':empty')(CSS :empty 選擇器同邏輯).html().trim() === '' 或 .text().trim() === ''isVisuallyEmpty(),處理註釋、隱藏元素、空白文本.val(),勿用 .html()/.text()