一键切换两个div [英] Toggling Between Two Divs by One Click Button

查看:101
本文介绍了一键切换两个div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用按钮单击事件切换两个元素(div)时遇到麻烦.我有一个此处的演示

I am having trouble on toggling two elements(divs) with button click event. I have a demo here

我的代码是这样的:

<div id="green"></div>
<div id="red"></div>
<button>Call Red</button>
<script>
$(document).ready(function(){
 $("button").click(function () {
  $("#green").show();
  $("#red").hide();
 });
});
</script>

和CSS看起来像:

#red {
    border:1px solid black;
    width:50px;
    height:50px;
    background-color:red;
}
#green {
    border:1px solid black;
    width:50px;
    height:50px;
    background-color:green;
    display:none;
}

我需要具有Toggle函数来更改两个div之间的可见性并更改 根据下一个颜色的按钮值.你能告诉我怎么做吗?

What I need is having a Toggle function to change visibilty between two divs and change the value of button based on next color. Can you please tell me how to do that?

推荐答案

function ButtonText() {
    if ($("#green").is(":visible")) {
        $("button").text("Call Red");
    } else {
        $("button").text("Call Green");
    }
}

ButtonText();
$("button").click(function () {
    $("#green").toggle();
    $("#red").toggle();
    ButtonText();
});

JSFIDDLE DEMO

您没有在小提琴中包含jQuery.

You didn't include jQuery in your fiddle.

这篇关于一键切换两个div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆