1

我的 html 的一部分是:

<tr id="row">
  <td abbr='selectme'>
    <div>Texti inside the div</div>
    Text outside the div
  </td>

  <td>
    any others I dont care about
  <td>
</tr>

我正在尝试选择具有属性'selectme'的 td 内部的“div 之外的文本” 。我怎样才能用jquery做到这一点?

我试过这样:

$("#row").find("[abbr='selectme']").text() 

但它什么也不返回。

4

3 回答 3

4

.text()还返回后代元素的文本内容,将它们过滤掉

var text = $("#row").find("[abbr='selectme']").contents().filter(function () {
    //select only text nodes of the targetted td element
    return this.nodeType == 3
}).text();

演示:小提琴

于 2014-02-03T14:04:11.113 回答
0

您没有得到任何回报的原因可能是因为您必须将其包装在一个

$( document ).ready(function() {}); or $(function(){});

因为 div 在通过 jquery 到达之前需要在 DOM 中加载,否则您正在访问尚未加载的元素。因此,通过使用此代码:

$(function () {
        alert($("#row").find("[abbr='selectme']").text());
});

您将获得以下文本: div 内的文本 div 外的文本

现在,由于您只想获取文本“div 外的文本”,它是纯文本,没有包含在任何标签中,您必须使用 .contetns().filter() 函数并获取

nodeType === 3

数值“3”用于获取文本节点。所以你的最终代码将如下所示(我使用警报进行说明)

 // Shorthand for $( document ).ready()
    $(function () {
        // getting the specific text and saving into a variable
        //getting the contents of the target element
        var myText = $("#row").find("[abbr='selectme']").contents()
        // using the filter to get the text node
            .filter(function () {
                return this.nodeType === 3;
            //getting the final text
            }).text();
        alert(myText);
    });

现在,当您运行程序时,您将得到输出“div 外的文本”。

这是工作示例http://jsfiddle.net/842nn/

于 2014-02-03T14:39:17.807 回答
0

您可以通过 attr 名称简单地搜索元素:

$("[abbr='selectme']").text();
于 2019-07-23T07:35:28.050 回答