我的班级有多个
.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>
答案 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>