JQuery 只获取元素的文本而不是子元素的文本

Aka*_*kam 6 html javascript jquery

我有一个大表,我需要将一些文本转换为另一个 Unicode 实体,但某些单元格包含另一个 html 元素,例如:

<td>some text <span>another text</span></td>
Run Code Online (Sandbox Code Playgroud)

我想得到some text只是因为我可以span通过以下方式得到第一个孩子:

children().eq(0)
Run Code Online (Sandbox Code Playgroud)

我试过

$(this).text() //but gets all text inside the cell
Run Code Online (Sandbox Code Playgroud)

Ibr*_*han 6

你可以some text像下面这样。

this.childNodes[0].nodeValue
Run Code Online (Sandbox Code Playgroud)

例子

this.childNodes[0].nodeValue
Run Code Online (Sandbox Code Playgroud)
$('td').click(function () {
    alert(this.childNodes[0].nodeValue)
}) 
Run Code Online (Sandbox Code Playgroud)

  • 使用`$('td#test')[0]`。像`$('td#test')[0].childNodes[0].nodeValue`。@阿卡姆 (2认同)