2008-11-07 149 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