由于某些原因,我必须从另一个包含页面设置页面部分。 首先看下面的inc.php页面:
page: inc.php
<?php
function sethead($javascript){
echo '<html><head>';
echo '<link rel="stylesheet" type="text/css" href="site.css" />';
echo '<script type="text/javascript" src="jquery1.9.1.js"></script>';
echo $javascript;
echo '</head>';
}
?>
inc.php页面包含sethead()函数,它将为每个页面设置头部,如下所示:
page: main.php
<?php
include('inc.php');
$javascript = '<script type="text/javascript" language="javascript">.......</script>';
sethead($javascript);
<body>
Here body codes go here
.....................
.....................
.....................
</body>
</html>
?>
main.php页面可以是任何页面,如secondpage.php,thirdpage.php ....等等。 但由于每个页面的javascript可能不同,所以我必须从sethead($ javascript)的函数参数回显这个javascript。但是在调用函数sethead($ javascript)之前,我找不到在main.php页面中声明这个javascript参数的合适方法,因为javascript代码包含几行难以放入变量的代码。
<script type="text/javascript" language="javascript">
document.oncontextmenu = function() {
return false;
}
window.onbeforeunload = function() {
return "Please don't reload this page.";
}
</script>
如何以简单的方式将上面的javascript代码放在变量/函数参数($ javascript)中?
答案 0 :(得分:1)
如果您只想更简单地定义多行变量,请使用NOWDOC:
$javascript = <<<'EOD'
<script type="text/javascript" language="javascript">
document.oncontextmenu = function() {
return false;
}
window.onbeforeunload = function() {
return "Please don't reload this page.";
}
</script>
EOD;
虽然在外部.js文件中编写javascript并将文件名传递给include可能更容易。
答案 1 :(得分:1)
PHP支持多行字符串,所以你可以简单地白:
$javascript = '
<script type="text/javascript" language="javascript">
document.oncontextmenu = function() {
return false;
}
window.onbeforeunload = function() {
return "Please don\'t reload this page.";
}
</script>
';
不要忘记逃避所有'
符号。
但我认为最好的决定是将js-code保存在js-file
中