请考虑以下HTML:
<td>
Some Text
<table>.....</table>
</td>
我需要操纵
td
元素的“某些文本”文本。我不应该触摸td
内部的table元素。因此,举例来说,也许我想将所有“e”替换为“@”。我用jQuery的.text()和.html()尝试了几种方法。我似乎总是从子表中选择某些内容,这是我不应该碰的。另外,不幸的是,我无法将“某些文本”包装到一个范围或div中。
最佳答案
$(function(){
$('td').contents().each(function(){
if(this.nodeType === 3)
$(this).replaceWith(this.wholeText.replace(/e/g, '#'));
});
});
或者像你建议的那样
$('td').contents().each(function(){
if(this.nodeType === 3)
this.data = this.wholeText.replace(/e/g, '#');
});
.contents()
交付所有元素,包括 textNodes 。