简体   繁体   English

jQuery过滤器函数,用于过滤一个类

[英]jquery filter function used to filter a class

A set of tr is there. 那里有一组tr。 and some tr pocess a class dblist_selected . 还有一些处理类dblist_selected I need to filter out the tr elements contain that class.I wrote a jquery code for that but its not working. 我需要过滤掉包含该类的tr元素,为此我编写了一个jQuery代码,但它不起作用。

<table>
    <tbody id="tbodyDashBoard">
        <tr id="tr0" class="heading">
            <th>heading</th>
        </tr>
        <tr id="tr1" class="itemrow dblist_selected">
            <td>itemname1</td>
        </tr>
        <tr id="tr2" class="itemrow dblist_selected">
            <td>itemname2</td>
        </tr>
        <tr id="tr3" class="itemrow">
            <td>itemname3</td>
        </tr>
        <tr id="tr4" class="itemrow">
            <td>itemname4</td>
        </tr>
        <tr id="tr5" class="itemrow">
            <td>itemname5</td>
        </tr>
        <tr id="tr6" class="itemrow">
            <td>itemname6</td>
        </tr>
        <tr id="tr7" class="itemrow">
            <td>itemname7</td>
        </tr>
    </tbody>
</table>

This is the jquery code statement. 这是jQuery代码语句。 I need the returned object in the variable selRow 我需要在变量selRow中返回的对象

var selRow = $("#divGridContainer").find("#tbodyDashBoard tr").filter(function () {
    return $(this).attr('class') == 'dblist_selected';
});

Is there any error in the code. 代码中是否有任何错误。 How can I achieve my goal 我如何实现我的目标

您可以将类选择器与类名一起使用,以dblist_selected类为目标元素:

var selRow = $("#divGridContainer").find("#tbodyDashBoard tr.dblist_selected")

Problem: 问题:

The problem in the code is that the value of the attribute class is compared to the classname, so if the element contains other class, the condition will not be satisfied. 代码中的问题是将属性类的值与类名进行比较,因此,如果元素包含其他类,则将不满足条件。

var selRow = $("#divGridContainer").find("#tbodyDashBoard tr").filter(function () {
    return $(this).attr('class') == 'dblist_selected';
});

For the elements the $(this).attr('class') will give string as 'itemrow dblist_selected' which is not equal to the string 'dblist_selected' . 对于元素, $(this).attr('class')将给出字符串作为'itemrow dblist_selected' ,它不等于字符串'dblist_selected' So, filtering will return no elements in the selRow variable. 因此,过滤将不会在selRow变量中返回任何元素。

Solution: 解:

Use hasClass() to check if an element is having specified class. 使用hasClass()检查元素是否具有指定的类。

var selRow = $("#divGridContainer").find("#tbodyDashBoard tr").filter(function () {
    return $(this).hasClass('dblist_selected');
});

There is no need to use filter , use descendant selector. 无需使用filter ,而使用后代选择器。

var selRow = $("#divGridContainer #tbodyDashBoard tr.dblist_selected");

You may access these elements directly: 您可以直接访问以下元素:

$("#divGridContainer").find("#tbodyDashBoard tr.dblist_selected").each( function (index, element) {
   // do stuff with element - jQuery(element)...
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM