Binding click function on each div JQuery
I need to bind the click function on each div of this ordered list in order to make hide/show an image on each imgXX div, I'm newbie with JQuery
<ol id='selectable'>
<li class="ui-state-default">
<div id="img01" class="img">
<div id="star01" class="star">
<img src="../ima/star.png" height="30px"/>
</div>
</div>
</li>
<li class="ui-state-default">
<div id="img02" class="img">
<div id="star02" class="star">
<img src="../ima/star.png" height="30px"/>
</div>开发者_如何转开发
</div>
</li>
</ol>
JQuery
$('div').each(function(){
$(this).click(function(){
if($(this).find('img').is(':visible').length){
$(this).find('img').fadeOut(700);
}
else{
$(this).find('img').fadeIn(700);
}
});
});
Try this:
$('div').each(function(){
$(this).click(function(){
if($(this).find('img').is(':visible')){
$(this).find('img').fadeOut(700);
}
else{
$(this).find('img').fadeIn(700);
}
});
});
The is
method returns a boolean. Use:
if($(this).find('img').is(':visible'))
or:
if($(this).find('img:visible').length)
Unlike the other filtering and traversal methods, .is() does not create a new jQuery object. Instead, it allows us to test the contents of a jQuery object without modification.
- Source : http://api.jquery.com/is/
So, you can not use length on it as it returns a boolean value. Remove 'length' and it should work.
I don't think you necessarily need the each.
$('div').click(function(){
var img = $(this).find('img');
if($(img).is(':visible')){
$(img).fadeOut(700);
}
});
Not sure about the nesting of the divs, but since you are requesting to only fade the img
I am assuming that the .star
div is visible and clickable. The function below is a bit more efficient as I am using children
instead of find
which is recursive. Other than the selectors this should work for you.
$('div.star').click(function() {
function () {
$(this).children('img').fadeOut(700);
},
function () {
$(this).children('img').fadeIn(700);
}
});
精彩评论