代码之家  ›  专栏  ›  技术社区  ›  Felix

在每个div JQuery上绑定click函数

  •  6
  • Felix  · 技术社区  · 15 年前

    <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>
    

    $('div').each(function(){
       $(this).click(function(){
              if($(this).find('img').is(':visible').length){
                        $(this).find('img').fadeOut(700);
              }
              else{
                        $(this).find('img').fadeIn(700);
                  }
       });
    });
    
    5 回复  |  直到 15 年前
        1
  •  5
  •   Guffa    15 年前

    这个 is

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

    或:

    if($(this).find('img:visible').length)
    
        2
  •  8
  •   Sidharth Panwar    15 年前

    试试这个:

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

    不同于其他过滤和 遍历方法,.is()没有 它允许我们测试 没有修改的jQuery对象。

    因此,不能对其使用length,因为它返回布尔值。删除'长度',它应该工作。

        4
  •  0
  •   Newtang    15 年前

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

    $('div').click(function(){
    
      var img = $(this).find('img');
    
      if($(img).is(':visible')){
        $(img).fadeOut(700);
      }
    
    });
    
        5
  •  0
  •   Dustin Laine    15 年前

    img 我假设 .star div可见并可单击。下面的函数在我使用时效率更高一些 children 而不是 find 这是递归的。除了选择器,这应该对你有用。

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