jquery find元素并将类添加到元素中

时间:2016-05-20 10:32:49

标签: javascript jquery

在进行函数调用时,尝试向li项中的元素添加类。我可以得到正确的输出值,但是找到孩子<i>证明是困难的。如果我能找到正确的嵌套<i>并添加课程&#39; show&#39;这将解决它:)

JS代码:

filterMarkers = function(category) {
    for (i = 0; i < markers1.length; i++) {
        marker = gmarkers1[i];
        // If is same category or category not picked
        if (marker.category == category || category.length === 0) {
            marker.setVisible(true);
            // Show the tick icon
            $(".filter").find("[data-value='" + category + "']").addClass('show');

        }
        // Categories don't match
        else {
            marker.setVisible(false);
        }
    }
}

HTML code:

<ul class="drop-down">
    <li class="filter blue" data-value="" onclick="filterMarkers('');">All <i class="fi-check"></i></li>
    <li class="filter yellow" data-value="test-one" onclick="filterMarkers('test-one');">Sales <i class="fi-check"></i></li>
    <li class="filter red" data-value="test-two" onclick="filterMarkers('test-two');">Incentives <i class="fi-check"></i></li>
    <li class="filter grey" data-value="test-three" onclick="filterMarkers('test-three');">Conferences <i class="fi-check"></i></li>
    <li class="filter orange" data-value="test-four" onclick="filterMarkers('test-four');">Team building <i class="fi-check"></i></li>
</ul>

2 个答案:

答案 0 :(得分:1)

查看filterMarkers方法,

  1. 要么只想显示作为参数传递的类别并隐藏其他所有内容

  2. 或者如果没有传递任何参数,则隐藏所有内容。

  3. 简化您的代码

    filterMarkers = function(category) {
        $(".filter").removeClass("show"); //remove show class from all
        if( category.length > 0 )
        {
           $(".filter[data-value='" + category + "']").addClass('show');
        }
        for (i = 0; i < markers1.length; i++) 
        {
            marker = gmarkers1[i];
            marker.category == category || category.length === 0 ? marker.setVisible( true ) : marker.setVisible( false );
            }
        }
    }
    

答案 1 :(得分:0)

$(".filter[data-value='" + category + "']").addClass('show');