jQuery and toggling between content divs
Ok, so this works fine for toggling one post on and off at a time. The script still can't see that it has to make the OTHER posts set to display = "none" when the user clicks on a new one. So if I click on the second post heading after the first, this needs to hide the content associated with the first and the div then displays text for the second post instead. And onward through multiple post titles. What's the best approach do you think? Here's the code that turns one topic on and off (click once to show, click again to hide). But clicking on one topic and then another increments the content together which isn't what I'd like... I know I've done this before like a year ago, I just can't remember how I did it.
<script type="text/javascript">
function togglePost(obj) {
var obj=document.getElementById(obj);
if (obj.style.display == "block") obj.style.display = "none";
else if (obj.style.display = "none") obj.style.display = "block";
else obj.style.display = "none";
}
</script>
<div id="container">
<div开发者_JAVA技巧 id="sidebar">
<h3>Posts</h3>
<p><span onClick="togglePost('q1')">October</span></p>
<p><span onClick="togglePost('q2')">November</span></p>
<p><span onClick="togglePost('q3')">December</span></p>
</div>
<div id="center">
<h1> Main Page of post content</h1>
<p><div id="q1" style="display:none;">October is...testtext testtext testtext</div></p>
<p><div id="q2" style="display:none;">November is...testtext testtext testtext</div></p>
<p><div id="q3" style="display:none;">December is...testtext testtext testtext</div></p>
</div>
<br class="clearfloat" />
</div>
In your function, just set them all to display = none, and then show the one you want.
function togglePost(obj) {
var obj=document.getElementById(obj);
var was_hidden = obj.style.display == "none";
$('[id^=q]').hide();
if (was_hidden) $(obj).show();
}
Use http://api.jquery.com/toggle/
Since you say jQuery in the question I'm gussing that's available
function togglePost(id) {
$('#center div').hide();
$('#' + id).show();
}
You could make your spans look like this:
<p><span class="q1">October</span></p>
<p><span class="q2">November</span></p>
<p><span class="q3">December</span></p>
And replace your Javascript with this:
$(document).ready(function() {
// unobtrusively attach onclick handlers to all span elements in the sidebar
// the className of each span corresponds to the ID of the div which it toggles
$("#sidebar span").click(function() {
$('#' + $(this).attr("class")).toggle();
});
});
Demo: http://jsfiddle.net/9Nqgs/
精彩评论