简体   繁体   English

用javascript动态显示和隐藏div

[英]dynamically showing and hiding divs with javascript

I currently have the following code for my login system: 目前,我的登录系统具有以下代码:

function handleLogin() {
    var e = $("#username").val();
    var p = $("#password").val();

    if(e != "" && p != "") {
        $.ajax({ 
            type: 'POST', 
            url: 'http://localhost/php/log.php', 
            crossDomain: true,
            data:  {username: e, password :p},
            dataType: 'json', 
            async: false,
            success: function (response) { 
                if (response.success) { 
                    alert("Your login worked");
                    $('#loginTest').html(e);
                } else {
                    alert("Your login failed");
                }
            },
            error: function(error) {
                alert('Could not connect to the database' + error);
            }
        }); 
    } else {
        alert("You must enter username and password");
    }
    return false;
}

When the login has worked, I get the correct alert, but then I want the login div to hide, and the div beneath it to show with the username (e) in it. 登录成功后,我会收到正确的警报,但是我希望隐藏登录div,并在其下面的div中显示用户名(e)。

So basically I just need to work out how to hide the current div, then show another one. 因此,基本上我只需要弄清楚如何隐藏当前的div,然后显示另一个div。

The login div is called #loginPage and the div below it is called #loginTest 登录div称为#loginPage,其下面的div称为#loginTest

You can use hide() and show() : 您可以使用hide()show()

if (response.success) { 
    $('#loginPage').hide();
    $('#loginTest').show().html(e);
} 

There are also fadeIn , fadeOut , slideUp , slideDown to deal with the display/hiding of elements. 也有fadeInfadeOutslideUpslideDown来处理元素的显示/隐藏。 You could even use animate to define your own transition. 您甚至可以使用animate来定义自己的过渡。 The API is always your friend in these situations. 在这种情况下, API始终是您的朋友。

To show and hide any particular HTML element you can use show() and hide() functions of that element. 要显示和隐藏任何特定的HTML元素,可以使用该元素的show()hide()函数。 Initially you can hide your loginTest div and only show loginPage div. 最初,您可以隐藏您的loginTest div,而仅显示loginPage div。

Try this: 尝试这个:

function (response) { 
                if (response.success) { 
                    $(#loginPage).hide(); //Hiding login page div
                    $(#loginTest).show(); //Showing login test div
                    alert("Your login worked");
                    $('#loginTest').html(e);
                } else {
                    alert("Your login failed");
                }

You can also add time for showing and hiding your DIV. 您还可以增加显示和隐藏DIV的时间。 Like $(#loginPage).hide("fast"); $(#loginPage).hide("fast"); and $(#loginTest).show("slow"); $(#loginTest).show("slow"); . It totally depends upon you what is your need. 这完全取决于您的需求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM