【问题标题】:Finding text in a table with jQuery使用 jQuery 在表格中查找文本
【发布时间】:2010-11-04 04:39:09
【问题描述】:

我有一个包含这样行的表:

<tr id="" class="objectRow">
  <td class="bulkSelector"><input id="" type="checkbox" value=""/></td>
  <td class="favorite"></td>
  <td class="name"><a id="" class="" href="">Ut Urna Nisl</a></td>
  <td class="description"><p>Nam feugiat tincidunt massa nec venenatis. Mauris egestas consectetur magna</p></td>
  <td class="modifiedDate"><p>5/20/2009</p></td>
</tr>

我想创建一个包含所有文本元素的 jQuery 包装集,然后我可以将它们发送到函数,如果它们不适合它们的单元格,将截断它们。

我不知道如何获得包装好的套装。

正在尝试这个,但它不起作用:

var textNodes = $('#resultsTable .objectRow')
.contents()
.filter(function(){ return this.nodeType == 3; })
.filter(function(){return this.nodeValue != null});

【问题讨论】:

    标签: jquery textnode


    【解决方案1】:

    jQuery 的text 函数返回元素的组合文本内容,因此您不必担心节点类型等。因此,您可以过滤所有文本内容为空白的元素:

    $('tr.objectRow', '#resultsTable').find('td').filter(function() {
        return $.trim($(this).text()) != '';
    });
    

    这将最终为您提供行中包含任何文本的所有 &lt;td&gt;s,您可以通过再次获取表格单元格的 text() 值来执行您想做的事情。

    关于您的评论,应该这样做:

    $('tr.objectRow', '#resultsTable').find('*').contents().filter(function() {
        return $.trim($(this).text()) != '';
    });
    

    【讨论】:

    • 谢谢。我没有问对问题。我需要的集合是包含文本的元素。在我的示例中,这将由一个 a 和 2 个 p 节点组成。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-12
    相关资源
    最近更新 更多