I have a map of a state with off of its counties sliced up as an image map. Instead of having a different function to click on each county and show its statistics is there a way to use something other than:
$('#county).click(function(){$(#countystats).slideToggle('fast');
100+ times for all the diffe开发者_如何学Pythonrent counties?
Whenever you have multiple elements that need to be styled the same or that you might need to pick up as a 'group', you can use a class instead of an id.
So if you want to attach a click handler to all county elements, you could add a class
attribute to each div
or span
or whatever and use that as the selector.
$('.county').click(function(){
$(this).find('.countystats').slideToggle('fast')
});
What this does is attach a click-listener to every element on the page that has class='county'
(for example, <div class='county'>
or even <img class='county'>
) and on click of that element, toggles it's descendent element with the countystats
class.
I'm assuming here that you have a separate countystats
element for each. If instead you have one <div>
with the id
countystats
, you can keep your original call
$('#countystats').slideToggle('fast');
but note that it looks like it will cause the countystats
to be toggled off with a second click so you probably want to change how that's handled. For example, I click on county 1, the stats slide into view. I click on county 2, the same handler is fired so the element is toggled off.
精彩评论