2008-11-07 150 views
1

我正在用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'); 
      }); 
+0

对不起,因为我的标记亚当严密;) – 2008-11-07 16:55:36

回答

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

这就是你想要的。它将选择您的列表中的所有子节点。在你的情况下,你的所有图像嵌套在列表元素内,所以这只会过滤掉你想要的东西。

1

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

$(this).siblings('img.expander').attr('src','img/content/info-close.gif'); 
+0

谢谢,毫无疑问,我的错,但我没有得到那个工作我自己... – 2008-11-07 17:00:37

+0

可能是因为img.expander是点击$(这个) ,而不是兄弟姐妹。 – Pistos 2008-11-07 17:02:24

2

如何使您的单击事件切换父项上的CSS类(在您的情况下,也许是ul.product-info)。然后,您可以使用CSS背景属性来更改<范围的背景图像,而不是使用文字<img>并试图摆弄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; 
} 

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

+0

ahah ...似乎是一个整洁的解决方案。会看看。 – 2008-11-07 17:03:24