找到最近的span元素并更改CSS类

Find closest span element and change the CSS Class

本文关键字:CSS 元素 最近 span      更新时间:2023-09-26

我的页面上有以下内容

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

我希望发生的是,当用户单击"查找商店"时,需要引用Id为V形的span标签,并且我需要将类V形向下更改为V形向上,我正试图使用以下代码

$('h5:not(#nutritionInfo)').click(function () {
if ($(this).find('span').hasClass("glyphicon glyphicon-chevron-down")) {
    $(this).find('span').removeClass("glyphicon glyphicon-chevron-down");
    $(this).find('span').addClass("glyphicon glyphicon-chevron-up");
} else {
    $(this).find('span').removeClass("glyphicon glyphicon-chevron-up");
    $(this).find('span').addClass("glyphicon glyphicon-chevron-down");
}
});

但在上面的代码中,它引用了"Find Store",并对其应用了一个V形,这样它就显示了两个。

如何引用Id为V形的另一个跨度标记并更改其上的V形?

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

全部由其中一个控制

$('.toggle-my-chevron').click(function () {
    $(this).find('span.glyphicon').
        toggleClass('glyphicon-chevron-down glyphicon-chevron-up');
});

您可以尝试这样做:您可以使用glyphicon类选择器找到span,然后删除/添加类。

注意-您已经使用了span id=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>

CSS

通过CSS应用图标图像,例如

h5 a {padding-right: 10px; background: transparent url('chevron-down.png') 100% 0 no-repeat}
h5 a.active {background: transparent url('chevron-up.png') 100% 0 no-repeat}

JS/JQUERY

$('h5 a').click(function(){
  $(this).toggleClass('active');
  return false;
});