Reputation: 717
I am dynamically creating a div class for a set of divs. The class corresponds with the class of another set of divs (also dynamically generated). I gave them the same class so as to be able to click on the div that displays by default and have the corresponding div appear (which is not displayed by default). The setup would be something like this with divs 'foo' being displayed and 'bar' being hidden
<div id="foo" class="one">1</div>
<div id="foo" class="two">2</div>
<div id="foo" class="three">3</div>
<div id="bar" class="one">One</div>
<div id="bar" class="two">Two</div>
<div id="bar" class="three">Three</div>
I dont know how to put this in jQuery. I know it is going to be a click function, I'm just not sure how to grab a class where I'm not sure what the value is. Any help is really appreciated!
Upvotes: 1
Views: 109
Reputation: 30721
you could write it like
<div id="foo_1" class="foo one">1</div>
<div id="foo_2" class="foo two">2</div>
<div id="foo_3" class="foo three">3</div>
<div id="bar_1" class="bar one">One</div>
<div id="bar_2" class="bar two">Two</div>
<div id="bar_3" class="bar three">Three</div>
<script type="text/javascript">
$('.foo').live('click',function(){
$('.bar').hide();
var classes = $(this).attr('class').split(/\s+/);
for(var i = 0; i < classes.length; i++){
if(classes[i] != 'foo'){
$('.bar.'+class[i]).show();
}
}
});
</script>
Upvotes: 0
Reputation: 83358
You cannot have multiple elements with the same id. It's unlikely anything will work correctly until that's fixed.
Are you looking for something like this:
<div class="foo one">1</div>
<div class="foo two">2</div>
<div class="foo three">3</div>
<div class="bar one">One</div>
<div class="bar two">Two</div>
<div class="bar three">Three</div>
Then when someone clicks on a foo
div:
$(document).on("click", "div.foo", function(){
$("div.foo:hidden:first").show();
});
Of course that obviates the need for the one
two
and three
classes. Did you want something like this:
<div class="foo foo1">1</div>
<div class="foo foo2">2</div>
<div class="foo foo3">3</div>
var nextToShow = 1;
$(document).on("click", "div.foo", function(){
$("div.foo" + nextToShow++).show();
});
Upvotes: 4
Reputation: 10403
As pointed out you must give different ids to your divs because each id given to html elements must be unique. However once fixed, in jQuery you could access and assign click event to dives by class
names like this:
$(".one, .two, .three").click(function(e){
alert("hello");
});
or you could collect divs by id
like this:
$("#foo, #bar").click(function(e){
alert("hello");
});
Upvotes: 0