开发者

jQuery function to check classes between two divs?

开发者 https://www.devze.com 2023-01-24 13:28 出处:网络
I\'ve got a page with two sets of div like so <div id=\"set1\"> <div class=\"1\"></div>

I've got a page with two sets of div like so

<div id="set1">
<div class="1"></div>
<div class="2"></div>
<div class="3"></div>
.....
<div class="n"></div>开发者_运维问答;
</div>

<div id="set2">
<div class="1"></div>
<div class="2"></div>
<div class="3"></div>
.....
<div class="n"></div>
</div>

"set2" is hidden on page load but each div needs to appear when the corresponding div in "set1" is clicked. For example, when "div#set1.1" is clicked, "div#set2.1" will show up. How can I do this with jQuery?

Thanks


This should work:

var set2 = $('#set2');

$('#set1 > div').click(function(){
    set2.find('.' + this.className).show();
});

We first cache #set2 for performance reasons, then attach a click event handler to each of the child div of #set1, which when clicked, will cause the corresponding div with the same class in #set2 to appear. See http://www.jsfiddle.net/yijiang/xCEVH/1/ for a simple demo.

However, class names starting with numbers are not valid in HTML. I've taken the liberty of correcting that mistake in the demo.


$('#set1 .1').click(function(event){
    $('#set2 .1').show();
})

This would add the feature. Repeat that for the other divs or use for-loops to automate this.


If parent div is hidden you won't be able to show any if its children. With jQuery you can do something like this:

hide all children of set2

#set2 div{
   display:none;
}

and then when item is clicked - show all items of that class.

$("#set1 div").click(function(){
   $('.'+ this.className).show();
});


 $('#set1').bind('click',function() {

    $('#2.'+$(this).attr('id').substring(2)).show();

    });
0

精彩评论

暂无评论...
验证码 换一张
取 消