PHP和JS是互聯網開發中最常用的編程語言之一,它們可以快速地創建動態、交互性網站。為了成為一名優秀的PHP和JS開發者,練習和挑戰自己的編程技能是非常必要的。下面,我將介紹一些常見的PHP和JS練習題。
1. 使用PHP創建一個簡單的計算器
<?php if(isset($_POST['submit'])){ $num1 = $_POST['num1']; $num2 = $_POST['num2']; $operator = $_POST['operator']; switch($operator){ case "add": $result = $num1 + $num2; break; case "subtract": $result = $num1 - $num2; break; case "multiply": $result = $num1 * $num2; break; case "divide": $result = $num1 / $num2; break; } } ?> <form method="post" action=""> <label>Num1:</label><input type="text" name="num1"><br> <label>Num2:</label><input type="text" name="num2"><br> <label>Operator:</label> <select name="operator"> <option value="add">+</option> <option value="subtract">-</option> <option value="multiply">*</option> <option value="divide">/</option> </select><br> <input type="submit" name="submit" value="Calculate"><br> </form> <?php if(isset($_POST['submit'])){ echo "Result: ".$result; } ?>
2. 創建一個簡單的JavaScript游戲
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>JavaScript Game</title> </head> <body> <button onclick="startGame()">Start Game</button> <p id="score">Score: 0</p> <div id="game"></div> <script> var score = 0; function startGame(){ //創建小球 var ball = document.createElement("div"); ball.className = "ball"; ball.style.top = Math.floor(Math.random()*300)+"px"; ball.style.left = Math.floor(Math.random()*800)+"px"; ball.onclick = function(){ this.parentNode.removeChild(this); score++; document.getElementById("score").innerHTML = "Score: "+score; } //將小球添加到游戲區域 document.getElementById("game").appendChild(ball); } </script> <style> .ball{ width: 50px; height: 50px; background: #f00; border-radius: 50%; position: absolute; } </style> </body> </html>
3. 使用PHP和JavaScript創建一個簡單的登錄系統
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Login System</title> </head> <body> <form method="post" action=""> <label>Username:</label><input type="text" name="username"><br> <label>Password:</label><input type="password" name="password"><br> <input type="submit" name="submit" value="Login"> </form> <script> //檢查是否登錄成功 <?php if(isset($_POST['submit'])){ $username = $_POST['username']; $password = $_POST['password']; if($username == "admin" && $password == "admin"){ echo "alert('Login successfully!');"; }else{ echo "alert('Login failed!');"; } } ?> </script> </body> </html>
以上是一些常見的PHP和JavaScript練習題,通過不斷地練習和挑戰自己,你會變得更加熟練。