jQuery:如何映射隐藏的元素

jQuery: How to map element which are hidden

本文关键字:隐藏 元素 映射 何映射 jQuery      更新时间:2023-09-26

我在表中有一些 TR,其中有类 parent_0 。我正在使用 jQuery map()来获取地图中所有未hidden的元素。

多姆:

<table id="tableID" class="tableClass">
<tbody>
    <tr>
        <th width="3px">Header1</th>
        <th align="left">Header2</th>
    </tr>
    <tr align="left">
        <td>Data1</td>
        <td><a <i id="1" class="parent_0" ></i>></a>Data12</td>
    </tr>
    <tr align="left" style="display: none;">
        <td>Data2</td>
        <td><a <i id="2" class="parent_0"></i>></a>Data22</td>
    </tr>
</tbody>

j查询:

$( document ).ready(function(){ 
    allChildern = $(".parent_0").map(function() {
        return this.id
    }).get();
    alert(allChildern)
    var allSubChildern = $(".parent_0").map(function() {
       if($('#'+this.id).closest('tr').is(':visible')){
           return this.id //its working but taking so much time for 1k records.
       }
    }).get();
    alert(allSubChildern)
});

是否有任何功能可以映射仅可见的元素。

这是小提琴。谢谢。

您可以使用

.filter()获取所有visible行,然后继续使用.map()

将匹配的

元素集减少为与选择器匹配或通过函数测试的元素集。

var allSubChildern = $(".parent_0").filter(function(){
    return $(this).closest('tr').is(':visible');
}).map(function() {
    return this.id;
}).get();
alert(allSubChildern)

或者,您也可以使用

var allSubChildern = $("#tableID tr:visible .parent_0").map(function() {
    return this.id;
}).get();

如果您真的担心性能并且可以更改 html,那么更好的解决方案是使用类来隐藏元素。

即,定义一个像.hidden{display: none}这样的类,然后在tr中使用它来隐藏元素(<tr align="left" class="hidden">而不是<tr align="left" style="display: none;">),这样你就可以使用纯CSS选择器来选择元素,这将提高速度,比如

  var allSubChildern = $("#tableID tr:not(.hidden) .parent_0").map(function() {
    return this.id;
  }).get();

使用:visible的模型大约需要 55-70 毫秒,而上述模型在小提琴中只需要 1-3 毫秒