2013-09-24 16 views
0

我试图创造一些猜谜游戏:显示隐藏的div提交(JavaScript的&PHP)

<?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 class="echo" id="hidden_div"> 

被隐藏在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会重新出现。谢谢。

回答

0

initialy使格为隐藏

<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> 
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中执行输出,因此您无需刷新页面即可获得答案。