问题
how can i use jQuery to show/hide the same div area... essentially swapping out content?
here is what i have so far, and i cant figure out how to hide the previous content and replace it with the new content:
<script type="text/javascript">
$(document).ready(function(){
$('.content').hide();
$('a').click(function(){
$('.content').show('slow');
});
//then hide previous content
});
</script>
<a href="#" id="a-link">A</a>
<a href="#" id="b-link">B</a>
<div class="start-content" id="a">
content here
</div>
<div class="content" id="b">
content here
</div>
回答1:
If you wrap the contents in a div, this would be a bit easier, like this:
<div id="wrap">
<div class="start-content" id="a">
content here
</div>
<div class="content" id="b">
content here
</div>
</div>
And this in jQuery:
$('a').click(function(){
$("#wrap > div").hide(); //hide previous
$('.content').show('slow'); //show what's clicked on
});
Since you have a convention with your IDs though, you can use that, either give you links a class, or wrap them as well, like this:
<div id="links">
<a href="#" id="a-link">A</a>
<a href="#" id="b-link">B</a>
</div>
<div id="wrap">
<div class="start-content" id="a">
content here
</div>
<div class="content" id="b">
content here
</div>
</div>
Then you could use a single event handler for all your links like this:
$('#wap > div:not(.start-content)').hide(); //Initial hide
$("#links a").click(function() {
$("#wrap > div").hide(); //hide previous
var id = $(this).attr("id").replace('-link', ''); //matching id
$('#' + id).show('slow'); //show what's clicked on
});
回答2:
Keep the content div visible; instead, just swap out the HTML content with
$('.content').html(strvalue);
来源:https://stackoverflow.com/questions/2546342/jquery-show-hide-replace-area