使用.hide()jquery后,Div重新出现

时间:2015-12-21 14:09:36

标签: javascript jquery html mysql css

我已经检查了所有类似的问题并尝试了不同的解决方案,但根本没有运气。

我有一个非常简单的div来获取姓名。我想要做的是,如果输入框不为空,则发布到另一页(使用jquery),删除或隐藏div1并显示div2以提出问题(div 2被隐藏)。

出于某种原因,当我点击提交按钮时,姓名和姓氏会发布到其他页面并存储在数据库中,但在警报之后,div1重新出现并且div 2消失。请问有人帮我一把吗?

非常感谢!

Jquery代码:

    <script>
        function saveDetailsToDB()
        {

            var name = document.getElementById('name').value;
            var surname = document.getElementById('surname').value;

            if (name === "" && surname === "") 
            {
                alert("Please, enter your details!");
                $("#UQ").css( "display", "none");   

            }

            else if(name !== "" && surname === "")
            {
                alert("Please, enter your Surname");
                $("#UQ").css( "display", "none");

            }

            else if(name === "" && surname !== "")
            {
                alert("Please, enter your Name");
                $("#UQ").css( "display", "none");
            }
            else
            {

                $.post("saveDetails.php",{ name: name,surname: surname });
                $("#detailsDiv").hide();
                $("#UQ").show();
                alert('You have been successfully registered!');

            }   
        }
    </script>

HTML:

    <div id = "detailsDiv">
        <form>
            <b><label>Name:</label></b><br> 
            <input type = "text" id = "name"><br><br>

            <b><label>Surname:</label></b><br>
            <input type = "text" id = "surname"><br><br>
            <button onclick="saveDetailsToDB();">Send</button>
        </form>

    </div>

    <div id = "UQ">
    <b><label>Please enter your question.</label></b><br><br>
    <form>
        <textarea id = "question" rows="4" cols="40"></textarea><br><br>
        <button onclick="saveQuestionToDB()">Save</button>
    </form>
</div>

1 个答案:

答案 0 :(得分:6)

问题是因为您没有阻止按钮点击的默认操作,因此页面重新加载会使内容看起来像重新出现。试试这个:

<button onclick="saveDetailsToDB(); return false;">Send</button>

或者更好的是,从HTML中删除过时的onclick属性并使用JavaScript附加事件:

<button class="btn-save">Send</button>
$(function() {
    $('.btn-save').click(function(e) {
        e.preventDefault();

        var name = $('#name').val();
        var surname = $('#surname').val();

        if (name === "" && surname === "") {
            alert("Please, enter your details!");
            $("#UQ").hide();
        }
        else if(name !== "" && surname === "") {
            alert("Please, enter your Surname");
            $("#UQ").hide();
        }
        else if(name === "" && surname !== "") {
            alert("Please, enter your Name");
            $("#UQ").hide();
        }
        else {
            $.post("saveDetails.php", { 
                name: name,
                surname: surname 
            });
            $("#detailsDiv").hide();
            $("#UQ").show();
            alert('You have been successfully registered!');
        }   
    });
});