2010-09-08 64 views
6

我需要点击功能绑定在这个排序列表中的每个格为了使隐藏/显示每个imgXX格的图像,我是新手用jQuery绑定点击函数div 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); 
       } 
    }); 
}); 
+1

那么,什么让你悲伤?嗯...($(this).find('img')。is(':visible')。长度不正确,我认为is()会给你一个真正的假,应用长度可能会很奇怪。 – 2010-09-08 05:59:52

+0

@Sidhart你说得对,应该是'find('img:visible')' – alex 2010-09-08 06:06:40

+0

请注意,你绑定了嵌套的div元素上的click事件,所以它们可能会触发两次,你可能想用'$(' div.img')''''或'$('div.star')'选出一组div元素,并且'.each(function(){$(this).click(...);}) ''可以缩短为'.click(...)',因为它将事件应用于集合中的所有元素。 – Guffa 2010-09-08 06:12:23

回答

5

is方法返回一个布尔值。用途:

if($(this).find('img').is(':visible')) 

或:

if($(this).find('img:visible').length) 
+0

很棒的节省时间 – 2014-07-30 06:42:04

8

试试这个:

$('div').each(function(){ 
    $(this).click(function(){ 
      if($(this).find('img').is(':visible')){ 
        $(this).find('img').fadeOut(700); 
      } 
      else{ 
        $(this).find('img').fadeIn(700); 
       } 
    }); 
}); 
1

不像其他过滤和 遍历方法,.is()不会 创建一个新的jQuery对象。相反, 它允许我们在不修改的情况下测试一个 jQuery对象的内容。

所以,你不能用它的长度,它返回一个布尔值。删除'长度',它应该工作。

0

我不认为你一定需要在每个。

$('div').click(function(){ 

    var img = $(this).find('img'); 

    if($(img).is(':visible')){ 
    $(img).fadeOut(700); 
    } 

}); 
+0

这工作正常? – kubudi 2012-03-07 21:35:24

0

不知道有关的div的嵌套,而是因为你是请求仅褪色img我假设.star DIV是可见的,可点击。下面的函数更有效一些,因为我使用的是children而不是find,它是递归的。除了选择器这应该为你工作。

$('div.star').click(function() { 
    function() { 
     $(this).children('img').fadeOut(700); 
    }, 
    function() { 
     $(this).children('img').fadeIn(700); 
    } 
});