SImple class-based jquery show/hide for multiple, independent instances?
Is there a way to have many, many instances开发者_运维知识库 of jquery-based show/hide (toggle link followed by container with hidden content; toggle text changes depending on state) on a page using only classes and not IDs? I haven't found a reasonably well-documented, functional example anywhere. Thanks for any and all help! --cg
Something like:
<div class="toggleset">
<a class="toggler" href="#">Hide</a>
<div class="container">
Data to show/hide
</div>
</div>
$('.toggler').click(function(evt) {
var $toggler = $(this);
var $container = $toggler.siblings('.container');
$container.toggle();
$toggler.text($container.is(':visible') ? "Hide" : "Show");
evt.preventDefault();
});
You don't need the outer div if you use next() instead of siblings, but it ties the script tighter to the markup.
Thanks a lot, Rob. Works well! I've managed to make it so secondary classes can control what the toggle text is in both states:
<script type="text/javascript">
<!--
$(document).ready(function() {
$('.toggler.show').click(function(evt) {
var $toggler = $(this);
var $container = $toggler.siblings('.container');
$container.toggle();
$toggler.text($container.is(':visible') ? "Show less" : "Show more");
$(this).toggleClass('active');
})
$('.toggler.read').click(function(evt) {
var $toggler = $(this);
var $container = $toggler.siblings('.container');
$container.toggle();
$toggler.text($container.is(':visible') ? "Read less" : "... Read more");
$(this).toggleClass('active');
})
evt.preventDefault();
});
-->
</script>
How would I take advantage of jquery "slide" toggle? I tried changing
$container.toggle();
to something like
$container.slideToggle('fast');
but that breaks the text change on the toggle. --cg
精彩评论