$("td[flag='title']").each(function(){
$(this).html(cutString($(this).html(), 5, "..."));
});
TD 結構:<td flag='title'>標題內容<a ...>|結果查看|</a></td>
$(this).html() 獲取包含標簽的 HTML 字符串,截取後可能破壞標簽結構(如截斷 <a> 標簽)。.html(newHtml) 重寫會導致事件綁定丟失、輸入框值重置等副作用。function truncateTextNodes(container, maxLen, suffix) {
container.contents().each(function() {
if (this.nodeType === Node.TEXT_NODE) {
var text = this.nodeValue;
if (text.length > maxLen) {
this.nodeValue = text.substring(0, maxLen) + suffix;
}
} else if (this.nodeType === Node.ELEMENT_NODE) {
// 遞歸處理子元素(可選:跳過 a、button 等交互元素)
if (!$(this).is('a, button, input, select')) {
truncateTextNodes($(this), maxLen, suffix);
}
}
});
}
$("td[flag='title']").each(function() {
truncateTextNodes($(this), 5, "...");
});
$("td[flag='title']").each(function() {
var $td = $(this);
// 克隆 TD,移除子元素獲取純文本
var clone = $td.clone();
clone.find('a, button, input').remove();
var pureText = clone.text().trim();
if (pureText.length > 5) {
// 僅修改首個文本節點
var firstTextNode = $td.contents().filter(function() {
return this.nodeType === Node.TEXT_NODE;
}).first();
if (firstTextNode.length) {
firstTextNode[0].nodeValue = pureText.substring(0, 5) + "...";
}
}
});
function cutString(str, len, suffix) {
if (!str || str.length <= len) return str;
return str.substring(0, len) + (suffix || "");
}
nodeValue 修改文本節點,保留 DOM 結構與事件。.text() 獲取純文本長度判斷,.html() 僅用於需保留標簽的場景。