document.getElementById("n")
在腳本里面php不能訪問html中的段落id="n"
。 該段落的內部html未被更改。 我也嘗試過使用jQuery,但它無法更改innerHTML
。php內部的javascript代碼無法訪問html元素。 document.getElementById不起作用
<?php
$username="root";
$password="";
$servername="localhost";
$database="mydb";
$conn=mysqli_connect($servername,$username,$password,$database);
if(!($conn)){
die(mysqli_connect_error());
}
$sql="select passenger from place where source='chennai' and destination='bengaluru'";
$result=mysqli_query($conn,$sql);
if(mysqli_num_rows($result)>0){
echo '<script>document.getElementById("n").innerHTML="Do Something";</script>';
}
mysqli_close($conn);
?>
<html>
<head lang="en-us">
<title>Cards</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="js/materialize.min.js"></script>
<script src="jquery-1.11.3.min.js"></script>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="css/materialize.min.css">
<link rel="stylesheet" href="demo_css.css">
</head>
<body>
<p id="n"></p>
<div class="container" id="con">
<div class="card hoverable">
<div class="card-content waves-effect waves-block waves-light">
<h1 class="card-title activator grey-text text-darken-4" id="content"></h1>
</div>
<div class="card-reveal">
<span class="card-title grey-text text-darken-4">Passengers<i class="material-icons right">close</i></span>
</div>
</div>
</div>
</body>
</html>
這是因爲php生成的js是在加載其餘的年齡之前執行的。如果你把它放在html塊下面,它應該可以工作。 – Jeff
..如果你已經在使用jQuery,你可以使用'$(document).ready()'來等待頁面的其餘部分被加載並準備訪問。或者像這裏使用香草js方法:http://stackoverflow.com/questions/9899372/pure-javascript-equivalent-to-jquerys-ready-how-to-call-a-function-when-the – Jeff
where is the JavaScript代碼?這裏只列出了php和html –