2011-01-13 56 views
0

我一個jQuery新手和IMG-孩子正在試圖端口a scriptjQuery的:將addClass()或removeClass()到P

它顯示一個餅圖圖像(初始類:「主」)和條形圖圖像(初始級:「二級」,不可見)爲相同的數據和觀衆可以點擊圖表餅圖和條形圖之間翻轉:

<style> 
     img.primary { 
       display: inline; 
       cursor: pointer; 
     } 
     img.secondary { 
       display: none; 
     } 
     p.chart:hover, img.secondary { 
       display: inline; 
       cursor: pointer; 
     } 
     p.chart:hover, img.primary { 
       display: none; 
     } 
</style> 

<script type="text/javascript" src="jquery-144.js"> 
</script> 

<script type="text/javascript"> 

$(function() { 
     // remove the "chart" class when the page loads, 
     // to disable hover for JavaScript-enabled users 
     $("p.chart").removeClass("chart"); 

     // XXX add a click-handler for P.chart here? 
}); 

// XXX how to rewrite this in jQuery? 
function swapImages(container) { 
     for (var child in container.childNodes) { 
       child = container.childNodes[child]; 
       if(child.nodeName == "IMG") 
         child.className = (child.className == "primary" ? "secondary" : "primary"); 
     } 
} 
</script> 

這裏是從網頁的摘錄:

<p class="chart" onclick="swapImages(this);"> 
<img class="primary" width=700 height=280 src="pie.png"> 
<img class="secondary" width=700 height=280 src="bar.png"> 
</p> 

(注意:the "p.chart" class is removed on load so that the charts flip between pie and bar on mouse-hover only for JavaScript disabled users

但我的實際問題是關於如何將swapImages()函數從純JavaScript重寫到jQuery。我也許應該叫:

$('p.chart').click(function(e) { 
     .... 
} 

,並呼籲addClass(「主」)removeClass(「次級」)那裏,但我失蹤瞭如何去通過所有IMG-孩子的位P.chart。

,做我需要調用$( 'p.chart')。點擊(....)$( 'p.chart')。每個()。單擊(....)

或者我可能不再需要p.chart了,只需將點擊處理程序直接指定給圖像?

謝謝!亞歷克斯

回答

0

你可以這樣做:

$(function(){ 
     $('p.chart').removeClass(chart); 
     $('p:has(img)').click(function(e){ 
     $("img", this).toggleClass("primary").toggleClass("secondary"); 
    }); 
    }); 

如果有兩個圖像,你需要切換對每個圖像點擊,你可以簡單地使用切換功能:

$(function(){ 
     $('p.chart').removeClass(chart); 
     $('p:has(img)').click(function(e){ 
     $("img", this).toggle(); 
     }); 
    }); 

編輯:更新根據OP的評論發佈該帖子。

+0

謝謝。我怎樣才能刪除「p.chart:hover」類? – 2011-01-13 23:04:05