<div class="movies">
<div class="movie" id="226260" movie-id="226260">
<div class="movie-header">
<h4 class="">Boyhood</h4>
<div class="movie-trailer-tools movie-tools">
<a class="add-trailer" data-toggle="modal" href="">
<img src="assets/images/_.gif" class="icon ic_b_table_add">
</a>
<a href="#" class="toggle-visibility">
<img src="assets/images/_.gif" class="icon ic_eye">
</a>
</div>
<div class="movie-link"></div>
</div>
</div>
</div>
<script>
$('.movies').on("click", '.toggle-visibility',function(event){
eyeImg = $(this).closest('.movie').children('.toggle-visibility').children('img');
var toRem = eyeImg.hasClass('ic_eye') ? 'ic_eye' : 'ic_eye_grey';
var toAdd = eyeImg.hasClass('ic_eye') ? 'ic_eye_grey' : 'ic_eye';
eyeImg.removeClass(toRem).addClass(toAdd);
});
</script>
我想改变课程&#34; icon ic_eye&#34;到&#34; icon ic_eye_grey&#34;反之亦然#34; toggle-visibility&#34;当用户点击图片时,我的jquery代码并没有正确执行。任何人都可以帮助我获得变量eyeImg的正确值吗?
顺便说一句,可能有多个div class =&#34; movie&#34;因为显示电影是在循环中。
答案 0 :(得分:3)
您要查找的img
是所点击的toggle-visibility
元素的子项,因此您可以在.find()
的上下文中使用this
来查找它。然后你可以使用toggleClass()来切换类
$('.movies').on("click", '.toggle-visibility', function(event) {
$(this).find('img').toggleClass('ic_eye_grey ic_eye');
event.preventDefault();
})
&#13;
.ic_eye {
border: 1px solid red;
}
.ic_eye_grey {
border: 1px solid green;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="movies">
<div class="movie" id="226260" movie-id="226260">
<div class="movie-header">
<h4 class="">Boyhood</h4>
<div class="movie-trailer-tools movie-tools">
<a class="add-trailer" data-toggle="modal" href="">
<img src="assets/images/_.gif" class="icon ic_b_table_add" />
</a>
<a href="#" class="toggle-visibility">
<img src="//placehold.it/16" class="icon ic_eye" />
</a>
</div>
<div class="movie-link"></div>
</div>
</div>
</div>
&#13;
答案 1 :(得分:1)
请更改:
eyeImg = $(this).closest('.movie').children('.toggle-visibility').children('img');
var toRem = eyeImg.hasClass('ic_eye') ? 'ic_eye' : 'ic_eye_grey';
var toAdd = eyeImg.hasClass('ic_eye') ? 'ic_eye_grey' : 'ic_eye';
eyeImg.removeClass(toRem).addClass(toAdd);
要:
var eyeImg = $(this).children('img');
eyeImg.toggleClass('ic_eye ic_eye_grey');