gpt4 book ai didi

javascript - jquery 查找元素并向元素添加类

转载 作者:行者123 更新时间:2023-12-03 06:54:25 26 4
gpt4 key购买 nike

在进行函数调用时尝试将类添加到 li 项内的元素。我可以获得正确的输出值,但是找到 child <i>事实证明很困难。如果我能找到正确的嵌套 <i>并添加类“show”来解决它:)

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 代码:

<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>

最佳答案

查看 filterMarkers 方法,您

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

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

简化您的代码

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 );
}
}
}

关于javascript - jquery 查找元素并向元素添加类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37344396/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com