what is the best way to toggle two divs in the same area
i am loading two divs in a page: divA and divB
i have divB display style = none.
I have a link that says "Show viewB". When i click this i want div B to show up wh开发者_JAVA技巧ere divA is and divA to hide.
i then want the link to change to "Show viewA"
what is the most elegant way of doing this in jquery?
By using the toggle()
function:
$("#link").toggle(function() {
toggleDivs();
$(this).html("Show viewA");
}, function() {
toggleDivs();
$(this).html("Show viewB");
});
function toggleDivs() {
$("#divA, #divB").toggle();
}
Very simple.
Example: http://jsfiddle.net/Zmsnd/
$('#toggle').click(function() {
$('#container > .toggleMe').toggle();
$(this).text(function(i,txt) { return txt === "Show viewB" ? "Show viewA" : "Show viewB"; });
});
This is my second try that I think that's more elegant than my original answer:
$("#link").click(function(e) {
e.preventDefault();
$("#divA, #divB").toggle();
$(this).text(function(i, text) { return (text == "Show viewA") ? "Show viewB" : "Show viewA" });
});
That's not very hard, try something like this:
var $divA = $('#a'),
$divB = $('#b'),
$link = $('#link');
// Initialize everything
$link.text( 'Show A' );
$divA.hide();
$link.click(function(){
// If A is visible when the link is clicked
// you need to hide A and show B
if( $divA.is( ':visible' ) ){
$link.text( 'Show A' );
$divA.hide();
$divB.show();
} else {
$link.text( 'Show B' );
$divA.show();
$divB.hide();
}
return false;
});
Example on jsFiddle
If the above answers don't give you the effect that you desire, you might want to try using the replaceWith
method instead (i.e., target.replaceWith(newContent)
). As the name suggests, it will replace the target
with the newContent
. The best part is that it will do it in-place.
divA.replaceWith(divB);
...
divB.replaceWith(divA);
var divA = $("#divA");
var divB = $("#divB");
var originalState = true;
$("#toggler").click(function(e) {
originalState = !originalState;
if (originalState) {
divB.hide();
divA.show();
} else {
divA.hide();
divB.show();
}
$(this).html(originalState ? "Show viewB" : "Show viewA");
e.preventDefault(); // Assuming you're using an anchor and "#" for the href
});
Here's my take on it:
$("#link").click(function() {
$("div[id^=tog_]").toggle();
$(this).text("Show " + $("div[id^=tog_]").not(":visible").attr("id").substr(4));
});
See it on JSFiddle.
Hope this helps.
精彩评论