我是PHP和PHTML的新手,我如何在PHTML中实现JavaScript?这是我试图将其实现的文件,(viewer.phtml)
<?php
if ($type == "jpeg") {
$stype = "jpg";
} else {
$stype = $type;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><?php echo APP_NAME . " - $file.$stype"; ?></title>
<link rel="stylesheet" href="/site/images/assets/css/style.css">
</head>
<body>
<h1><?php echo "$file.$type"; ?></h1>
<div class="container">
<img src="/images/<?php echo "$type/$file.$stype"; ?>" alt="<?php echo "$file.$stype"; ?>">
</div>
<?php
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$finish = $time;
$total_time = round(($finish - $start), 4);
?>
</body>
</html>
答案 0 :(得分:1)
添加脚本使用脚本标记。将它注入头部标签内,这样你的头部可能看起来像这样
<head>
<meta charset="UTF-8">
<title><?php echo APP_NAME . " - $file.$stype"; ?></title>
<link rel="stylesheet" href="/site/images/assets/css/style.css">
<script>
//you Javascript code here
</script>
</head>
或
<head>
<meta charset="UTF-8">
<title><?php echo APP_NAME . " - $file.$stype"; ?></title>
<link rel="stylesheet" href="/site/images/assets/css/style.css">
<script type="text/javascript" src="your_js_file_location_here"></script>
</head>
希望这会对你有所帮助
答案 1 :(得分:0)
可以像添加HTML一样添加JavaScript。 您可以在PHP标记之外添加它 或者您可以使用echo输出您的javascript文本。
示例1:
<?php
//my PHP
?>
<html>
<head>
<script>alert('hello');</script>
</head>
<body>
</body>
</html>
示例2
<html>
<head>
<script><?php echo "alert('hello');" ?></script>
</head>
<body>
</body>
</html>
请注意,一旦将页面或文本发送到浏览器,javascript就无法直接访问PHP变量,而无需通过ajax回调服务器。
实施例
<?php
$message="hello";
?>
<html>
<head>
<script>
//this won't work right
alert('<?php $message ?>');</script>
<script>
//this will alert the value of $message at the time echo was called
alert('<?php echo $message ?>');</script>
</head>
<body>
</body>
</html>
<?php
//!!! This won't matter to the javascript alerts, even though its PHP value has changed.
$message='goodbye';
?>