在表单提交上显示隐藏的div(javascript& PHP)

时间:2013-09-24 03:50:58

标签: javascript php html forms submit

我正在尝试创建一个数字猜谜游戏:

<?php
    $num = rand(1,1000);
    $guess = $_POST["guess"];
?>

<div class="intro">We've generated a random number between 1 and 100. Give us your best guess!</div>

<form action="index.php" method="post">
    <input type="text" name="guess">
    <input type="submit" value="Guess!" onsubmit="showHide()">
</form>

<div class="guess-text">Your guess was <span class="guess-var"><?php echo $guess; ?></span></div>

<div class="echo" id="hidden_div>
<?php
    if ($guess > $random) {
    echo "Sorry, too high! Better luck next number!";
    }

elseif ($guess < $random) {
echo "Sorry, too low! Better luck next number!";
    }

else {
    echo "<script type='text/javascript'>location.href='/youwin.html'</script>";
}
?>
</div>

我想要显示结果的div

<div class="echo" id="hidden_div">

在提交表单之前一直隐藏。这是我能找到的唯一能帮助我的代码:

<script type="text/javascript">
    function showHide() {
        var div = document.getElementById("hidden_div");
        if (div.style.display == 'none') {
            div.style.display = '';
        }

        else {
            div.style.display = 'none';
        }
    }
</script>

不幸的是,这只是隐藏了div。我需要一些帮助来确保在提交猜测后div会重新出现。感谢。

2 个答案:

答案 0 :(得分:1)

你可以在不使用Javascript的情况下完成它,使其更清晰......

<?php if(isset($_POST["guess"]) && $_POST["guess"]!=""){ //only show if 'guess' is posted?>
 <div class="echo" id="hidden_div>

    if ($guess > $random) {
       echo "Sorry, too high! Better luck next number!";
    }

 elseif ($guess < $random) {
 echo "Sorry, too low! Better luck next number!";
    }

 else {
    echo "<script type='text/javascript'>location.href='/youwin.html'</script>";
 }
 ?>
 </div>
<?php } ?>

另一个选项是直接在Javascript中输出,因此您无需刷新页面即可获得答案。

答案 1 :(得分:0)

初始化div为隐藏

<div class="echo" id="hidden_div" style="display:none">
<?php
    if ($guess > $random) {
    echo "Sorry, too high! Better luck next number!";
    }

elseif ($guess < $random) {
echo "Sorry, too low! Better luck next number!";
    }

else {
    echo "<script type='text/javascript'>location.href='/youwin.html'</script>";
}
?>
</div>

点击按钮

<input type="submit" value="Guess!" id="btn" name="btn" onclick="showHide()">

<script type="text/javascript">
    function showHide() {
            document.getElementById("hidden_div").style.display = "block";
    }
</script>