使用jQuery更改单击的div内的锚标记的css

时间:2019-03-02 12:59:37

标签: javascript jquery html css

我的班级有多个

  

.product_wishlist

我想更改用户在该div内单击的特定锚标签的颜色,但是现在.pw div内的所有锚标签颜色都已更改。是否可以将选定的CSS添加到clicked元素中。请帮助解决我的问题。

$(document).ready(function() {
  $(document).on('click','.pw',function(e){
    $('.pw > a').css('background-color', 'green');
  });
});
.product_wishlist > a {
    background-color: #e91e63;
    height: 30px;
    position: absolute;
    right: -32px;
    text-align: center;
    top: 15px;
    width: 30px;
    -webkit-transition-duration: 500ms;
    transition-duration: 500ms;
    z-index: 9;
}

.wishlish-selected > a {
    background-color: black;
    height: 30px;
    position: absolute;
    right: -32px;
    text-align: center;
    top: 15px;
    width: 30px;
    -webkit-transition-duration: 500ms;
    transition-duration: 500ms;
    z-index: 9;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<div class="product_wishlist pw">
  <a href="#" target="_blank"><i class="ti-heart"></i>Wishlist</a>
</div>

1 个答案:

答案 0 :(得分:0)

使用this来引用当前元素,并使用.find()来引用 anchor 元素:

更改

$('.pw > a').css('background-color', 'green');

收件人

$(this).find('a').css('background-color', 'green');

$(document).ready(function() {
  $(document).on('click','.pw',function(e){
    $(this).find('a').addClass('wishlish-selected')
  });
});
.wishlish-selected{
  background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<div class="product_wishlist pw">
  <a href="#" target="_blank"><i class="ti-heart"></i>Wishlist 1</a>
</div>
<div class="product_wishlist pw">
  <a href="#" target="_blank"><i class="ti-heart"></i>Wishlist 2</a>
</div>
<div class="product_wishlist pw">
  <a href="#" target="_blank"><i class="ti-heart"></i>Wishlist 3</a>
</div>

由于您已经在CSS选择器中的类之后指定了 anchor 元素,因此无需在jQuery中再次找到 anchor 元素,只需将类添加到当前元素。另外,position: absolute存在问题,以显示我在此处忽略该属性的输出:

$(document).ready(function() {
  $(document).on('click','.pw',function(e){
    $(this).addClass('wishlish-selected')
  });
});
.product_wishlist > a {
    background-color: #e91e63;
    height: 30px;
    right: -32px;
    text-align: center;
    top: 15px;
    width: 30px;
    -webkit-transition-duration: 500ms;
    transition-duration: 500ms;
    z-index: 9;
}

.wishlish-selected > a {
    background-color: black;
    height: 30px;
    right: -32px;
    text-align: center;
    top: 15px;
    width: 30px;
    -webkit-transition-duration: 500ms;
    transition-duration: 500ms;
    z-index: 9;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<div class="product_wishlist pw">
  <a href="#" target="_blank"><i class="ti-heart"></i>Wishlist 1</a>
</div>
<div class="product_wishlist pw">
  <a href="#" target="_blank"><i class="ti-heart"></i>Wishlist 2</a>
</div>
<div class="product_wishlist pw">
  <a href="#" target="_blank"><i class="ti-heart"></i>Wishlist 3</a>
</div>