Php 在加载时调用 javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13060419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Php calling javascript on load
提问by Veljko89
Guys i have little problem with PHP to call Javascript function on load ... Idea is when page load i do little calculation with PHP stuff , so when i finish that all i want is to write that down in same DOM element using javascript. I will not show you PHP code for calculation as i am 100% sure it is alright. This is the code i got so far , so can you just tell me whats wrong with it?
伙计们,我对 PHP 在加载时调用 Javascript 函数没有什么问题......想法是当页面加载时我很少用 PHP 计算,所以当我完成我想要的就是使用 javascript 在同一个 DOM 元素中写下它。我不会向您展示用于计算的 PHP 代码,因为我 100% 确定它没问题。这是我到目前为止得到的代码,所以你能告诉我它有什么问题吗?
$test = 100;
echo "<script language=javascript> window.onload=UpdatePoints($test); </script>";
and Javascript function is simple
和 Javascript 功能很简单
function UpdatePoints(Points) {
document.getElementById('PointsNumber').innerHTML = Points;
}
Thanks in advance
提前致谢
回答by Michael Berkowski
Instead of calling the function UpdatePoints()
in window.onload
, you need to wrap the call in a function that gets assigned by reference to window.onload
. Otherwise, you are calling the function, and assigning its return value to window.onload
.
您需要将调用包装在通过引用分配给 的函数UpdatePoints()
中window.onload
,而不是在 中调用函数window.onload
。否则,您正在调用该函数,并将其返回值分配给window.onload
.
// This function wraps UpdatePoints($test)
// and is assigned as a reference to window.onload
function load() {
UpdatePoints(<?php echo $test; ?>);
}
echo "<script type='text/javascript'> window.onload=load; </script>";
Note that the language
attribute to the <script>
tag is deprecated. Include a type=text/javascript
attribute in its place (though text/javascript is genearlly the browser default)
请注意,标签的language
属性<script>
已被弃用。type=text/javascript
在其位置包含一个属性(尽管 text/javascript 通常是浏览器的默认设置)
However, since the value of $test
is created before the page loads and cannot change when the function is called, you might as well not bother passing it as a parameter, in which case you don't need to wrap the function. Just remove the ()
to assign it as a reference.
但是,由于 的值$test
是在页面加载之前创建的,并且在调用函数时无法更改,因此您最好不要将其作为参数传递,在这种情况下,您不需要包装函数。只需删除()
即可将其分配为参考。
echo "<script type='text/javascript'> window.onload=UpdatePoints; </script>";
function UpdatePoints() {
// PHP write directly into the function since the value
// can't change... It's always going to be passed as what PHP assigns
// if you call it as UpdatePoints($test)
var Points = $test;
document.getElementById('PointsNumber').innerHTML = Points;
}