jQuery函数用于选择具有相同类的多个元素中的一个元素

时间:2017-08-04 10:12:00

标签: jquery

我想创建一个可以重用的函数,这就是为什么函数都是在lol.Anyways之后生成的,代码如下:

<div id="shot_filters">
  <a href="#" id="filter_active">
    <span class="filter_row_down"></span> By date </a>
  <a href="#">
    <span class="filter_row_down"></span> By likes </a>
  <a href="#">
    <span class="filter_row_down"></span> By views </a>
  <span class="filter_p"></span>
  <a href="#" class="tags_flip"><img src="static/img/retina/tags_icon.png" style="width: 13px; height: 14px">Tag search</a>
  <span class="filter_p"></span>
  <a href="#"><img src="static/img/retina/gallery_icon.png" style="width: 13px; height: 12px">Beauty gallery</a>
</div>

我想要的是制作这样的功能:

function changeClass(name)

从我想要的多个href及其类中我想要点击它们来更改自己的CSS。例如:我点击By likes,它会更改span类,添加一个href id作为filter_active并从中删除filter_active另一个。

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

您应该为要侦听的每个元素创建单独的侦听器。

&#13;
&#13;
$("a").each(function(){
   $(this).click(function(){
        $(this).toggleClass("class1");
   });
});
&#13;
a::after{
  content: "\A";
  white-space: pre;
}
.baseclass{
  cursor:pointer;
  color: blue;
}
.class1{
  color: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="baseclass class1">Row : Click Me</a>
<a class="baseclass class1">Row : Click Me</a>
<a class="baseclass class1">Row : Click Me</a>
<a class="baseclass class1">Row : Click Me</a>
<a class="baseclass class1">Row : Click Me</a>
<a class="baseclass class1">Row : Click Me</a>
<a class="baseclass class1">Row : Click Me</a>
<a class="baseclass class1">Row : Click Me</a>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

&#13;
&#13;
$(function(){
  $('#shot_filters a').on('click',function(){
      $('#shot_filters a').removeClass('active');
      $(this).addClass('active');
  })
})
&#13;
.active{
color:red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="shot_filters">

    <a href="#" id="filter_active">
        <span class="filter_row_down"></span>
        By date				</a>

    <a href="#">
        <span class="filter_row_down"></span>
        By likes				</a>

    <a href="#">
        <span class="filter_row_down"></span>
        By views				</a>

    <span class="filter_p"></span>
    <a href="#" class="tags_flip">
        <img src="static/img/retina/tags_icon.png" style="width: 13px; height: 14px">Tag search</a>

    <span class="filter_p"></span>
    <a href="#">
        <img src="static/img/retina/gallery_icon.png" style="width: 13px; height: 12px">Beauty gallery</a>

</div>
&#13;
&#13;
&#13;

嘿,当用户点击单个标签时,你需要在每个锚标签上都有一个事件,然后你需要添加活动类并从这样的方式中删除。