Proper way to communicate between divs in jquery?
This is probably a simple question, and i'm just being dense. I've looked through a few jquery books and nothing has jumped out at me, i'm probably missing something.
I'm looking for the 'proper', best practices way to communicate between divs/dom items on a page?
For example, I have a page with 5 panels that display when a link is chosen, they hide/show/run some code that changes other pieces on the page. Something like this snippet:
<ul>
<li><div id="unique_name_1_anchor">Unique div 1</div></li>
<li><div id="unique_name_2_anchor">Unique div 2</div></li>
<li><div id="unique_name_3_anchor">Unique div 3</div></li>
<li><div id="unique_name_4_anchor">Unique div 4</div></li>
</ul>
...Somewhere else on the page
<div id="unique_name_1_panel">Some panel 1 stuff here开发者_开发百科</div>
<div id="unique_name_2_panel">Some panel2 stuff here<div>
<div id="unique_name_3_panel">Some panel3 here</div>
<div id="unique_name_4_panel">Some panel4 here</div>
The concept being when as user clicks on a unique_name_X_anchor div, some action is performed on the corresponding panel (ie show/hide etc...). What I have been doing now is parsing the id ie ($(this).replace("_anchor","_panel") to get the div id of the other dom element. This just seems clunky and there must be a better/more proper way of doing this. Suggestions?
Thanks
A few ideas:
using the jQuery metadata plugin to add some metadata that points to the corresponding DIV. http://plugins.jquery.com/project/metadata
Get creative, use another valid DOM element or valid attribute (rel, href) to hold this info
If you have this data programmatically, set
$('.anchor').data('correspondingPanel')
to the corresponding ID (or some other useful data).If indexes will always be the same use the jQuery index method to get the index of the anchor, and show the panel with the same index. http://api.jquery.com/index/
Need you use id
's? Would this approach be appropriate?
HTML
<ul id="anchors">
<li><div>Unique div 1</div></li>
<li><div>Unique div 2</div></li>
<li><div>Unique div 3</div></li>
<li><div>Unique div 4</div></li>
</ul>
<div id="panels">
<div>Some panel 1 stuff here</div>
<div>Some panel2 stuff here<div>
<div>Some panel3 here</div>
<div>Some panel4 here</div>
</div>
jQuery
$('#anchors div').click(function() {
var panel = $('#panels div').eq($(this).index());
panel.show();
})
One way is creatively use class names for this.
Given:
<div id="unique_name_1_anchor">Unique div 1</div>
<div class="unique_name_1_anchor">Div 1 panel</div>
You could do something like:
$('#unique_name_1_anchor).click(function(){$('.'+this.id).show()})
something along the line of
give li div a class called divLinks give panel div class called pabel
$('div.divLinks').click(function(){
$('.panel').hide();
$('.panel').eq($(this).index()).show();
});
精彩评论