I'm a jQuery newbie and am trying to port a script
It displays a pie chart image (initial class: "primary") and a bar chart image (initial class: "secondary", not visible) for the same data and viewers can click the chart to flip between pie and bar:
<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>
And here is an excerpt from the web page:
<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>
(Note: 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)
But my actual question is about how to rewrite the swapImages() function from pure JavaScript to jQuery. I probably should call:
$('p.chart').click(function(e) {
....
}
and call addClass("primary") or removeClass("secondary") there, but I'm missing the bit on how to go through all IMG-children of that P.chart.
And do I need to call $('p.chart').click(....) or $('p.chart').each().click(....) ?
Or maybe I don't need p.chart her开发者_StackOverflowe anymore and just assign click-handlers directly to the images?
Thank you! Alex
You can do this:
$(function(){
$('p.chart').removeClass(chart);
$('p:has(img)').click(function(e){
$("img", this).toggleClass("primary").toggleClass("secondary");
});
});
If there are two images and you need to toggle the images on each click you can simply use the toggle function:
$(function(){
$('p.chart').removeClass(chart);
$('p:has(img)').click(function(e){
$("img", this).toggle();
});
});
Edit: Updated the post as per the comment by OP.
精彩评论