Javascript 查找最近的span元素并更改CSS类
我的页面上有以下内容Javascript 查找最近的span元素并更改CSS类,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我的页面上有以下内容 <h5 class="text-center" id="findStore" style="width:260px"> <a data-toggle="collapse" data-parent="#accordion" href="#@item.ProductId" aria-expanded="true" aria-controls="@item.ProductId" style="color: @item.ProductTextColor;f
<h5 class="text-center" id="findStore" style="width:260px">
<a data-toggle="collapse" data-parent="#accordion" href="#@item.ProductId" aria-expanded="true" aria-controls="@item.ProductId" style="color: @item.ProductTextColor;font-size:19px;text-decoration: none;" class="text-center">
<span class="text-center" style="margin-left:14%">FIND A STORE</span>
<span id="chevvy" class="glyphicon glyphicon-chevron-down pull-right"></span>
</a>
</h5>
但在上面的代码中,它引用了“findstore”,并对其应用了一个V形符号,因此它显示了两个
如何引用Id为chevvy的另一个span标记并更改其上的V形?您可以尝试以下方法:使用
glyphicon
类选择器查找span,然后删除/添加类
注意-您使用了spanid=chevvy
,如果您有多个这样的span,请确保必须为每个DOM元素使用唯一的id
$('h5:not(#nutritionInfo)').click(function () {
var span = $(this).find('.glyphicon');
if ($(span).hasClass("glyphicon-chevron-down")) {
$(span).removeClass("glyphicon-chevron-down").addClass("glyphicon-chevron-up");
} else {
$(span).addClass("glyphicon-chevron-down").removeClass("glyphicon-chevron-up");
}
});
你需要优化你的HTML和CSS,因为你的代码片段中有多余的HTML,这将有助于清理JS。下面是一个您可以做的快速示例: HTML
<h5 class="text-center" id="findStore">
<a href="#" class="">FIND A STORE</a>
</h5>
JS/JQUERY
$('h5 a').click(function(){
$(this).toggleClass('active');
return false;
});
您的find('span')
正在查找所有跨度,但您只想触摸其中一个。通过添加更多选择器缩小范围,如find('span.glyphicon')
顺便说一句,您可以不使用glyphicon
类,而使用jQuery的toggleClass
功能来切换-up
和-down
,而不使用所有if-else:
$('h5:not(#nutritionInfo)').click(function () {
$(this).find('span.glyphicon').
toggleClass('glyphicon-chevron-down glyphicon-chevron-up');
});
您还可以考虑使用伪类而不是ID来确定哪些H5元素获得此行为。例如,你可以有一堆这样的东西
<h5 class="toggle-my-chevron">...</h5>
<h5 class="toggle-my-chevron">...</h5>
“雪佛兰”这个项目就是为了这个图标吗?那么谁投了反对票?有什么解释吗?
$('h5:not(#nutritionInfo)').click(function () {
$(this).find('span.glyphicon').
toggleClass('glyphicon-chevron-down glyphicon-chevron-up');
});
<h5 class="toggle-my-chevron">...</h5>
<h5 class="toggle-my-chevron">...</h5>
$('.toggle-my-chevron').click(function () {
$(this).find('span.glyphicon').
toggleClass('glyphicon-chevron-down glyphicon-chevron-up');
});