打开/关闭图标

时间:2008-11-07 16:34:24

标签: javascript jquery html dom

我正在用jQuery做一些shennanigans,在我的扩展器旁边添加一些加/减图标。它类似于windows文件树或firebugs代码扩展器。

它有效,但不够具体。

希望这是有道理的......

$('div.toggle').hide();//hide all divs that are part of the expand/collapse
$('ul.product-info li a').toggle(function(event){
  event.preventDefault();
  $(this).next('div').slideToggle(200);//find the next div and sliiiide it
  $('img.expander').attr('src','img/content/info-close.gif');//this is the part thats not specific enough!!!
},function(event) { // opposite here
  event.preventDefault();
  $(this).next('div').slideToggle(200);
  $('img.expander').attr('src','img/content/info-open.gif');
});


<ul class="product-info">
  <li>
    <a class="img-link" href="#"><img class="expander" src="img/content/info-open.gif" alt="Click to exand this section" /> <span>How it compares to the other options</span>
  </a>
  <div class="toggle"><p>Content viewable when expanded!</p></div>
  </li>
</ul>

页面上有大量$('img.expander')个标签,但我需要具体。我已经尝试了next()功能(就像我以前用来查找下一个div),但是它说它未定义。如何找到我的特定img.expander标签?感谢。

编辑,根据道格拉斯的解决方案更新代码:

$('div.toggle').hide();
            $('ul.product-info li a').toggle(function(event){
                //$('#faq-copy .answer').hide();
                event.preventDefault();
                $(this).next('div').slideToggle(200);
                $(this).contents('img.expander').attr('src','img/content/info-close.gif');
                //alert('on');
            },function(event) { // same here
                event.preventDefault();
                $(this).next('div').slideToggle(200);
                $(this).contents('img.expander').attr('src','img/content/info-open.gif');
            });

3 个答案:

答案 0 :(得分:5)

$(this).contents('img.expander')

这就是你想要的。它将选择列表中所有子节点。在您的情况下,您的所有图像都嵌套在list元素中,因此这将仅过滤掉您想要的内容。

答案 1 :(得分:2)

如何使您的点击事件在父项上切换CSS类(在您的情况下,可能是ul.product-info)。然后,您可以使用CSS背景属性更改&lt; span&gt;的背景图像。而不是使用文字&lt; img&gt;并试图摆弄src。您还可以在div.toggle上完成显示和隐藏。

ul.product-info.open span.toggler {
   background-image: url( "open-toggler.png" );
}
ul.product-info.closed span.toggler {
   background-image: url( "closed-toggler.png" );
}

ul.product-info.open div.toggle {
   display: block;
}
ul.product-info.closed div.toggle {
   display: hidden;
}

当DOM有许多项目和深度嵌套时,使用jQuery导航/蜘蛛网功能可能会很慢。使用CSS,您的浏览器将更快地呈现和更改内容。

答案 2 :(得分:1)

您是否尝试过.siblings()方法?

$(this).siblings('img.expander').attr('src','img/content/info-close.gif');
相关问题