3 回答

TA貢獻(xiàn)1783條經(jīng)驗(yàn) 獲得超4個(gè)贊
就性能而言,當(dāng)前接受的答案非??膳?,因此我不得不寫一個(gè)更輕量的答案:
$.fn.mytext = function() {
var str = '';
this.contents().each(function() {
if (this.nodeType == 3) {
str += this.textContent || this.innerText || '';
}
});
return str;
};
console.log($('#mydiv').mytext());

TA貢獻(xiàn)1777條經(jīng)驗(yàn) 獲得超10個(gè)贊
就像Ja?ck的答案一樣,但無需顯式迭代(通過.each())并收集textContents:
$('#mydiv').contents().filter(function(){return this.nodeType === 3}).text()
或者,如果可以使用箭頭功能:
$('#mydiv').contents().filter((i, el) => el.nodeType === 3).text()
添加回答
舉報(bào)