英文:
window.onload and window.beforeunload not working while trying to update and display a variable
问题
<html>
<head>
<script type="text/javascript">
var VisOn;
function load() {
VisOn = VisOn + 1;
return VisOn;
}
function leave() {
VisOn = VisOn - 1;
return VisOn;
}
window.onbeforeunload = leave;
window.onload = load;
</script>
</head>
<style>
body {background-color: lightyellow}
h1 {color:blue}
</style>
<body>
<form>
<br>
value is :
<script type="text/javascript">
document.write(VisOn)
</script>
</form>
<br>
</body>
</html>
英文:
So i want to increment a variable when a user loads my website, and decrease that variable when a user leaves.
The output I'm getting is: "Value is : undefined"
which makes sense if the variable wasn't being incremented and left undefined. This leads me to believe the onload and onbeforeload functions aren't being executed. HOWEVER, with this code, when a user leaves the website they are prompted with an alert which leads me to believe the functions are being executed while the variable isn't being increment or decreased for some reason.
I am testing the connections from my laptop using firefox and my raspberry pi using the default browser.
What i was expecting was the variable VisOn to increase by 1 when my laptop connects to the website and would display: "Value is : 2" when my pi and laptop are both connected.
the code is posted below:
<html>
<head>
<script type="text/javascript">
var VisOn;
function load()
{
VisOn = VisOn +1 ;
return VisOn;
}
function leave()
{
VisOn = VisOn -1 ;
return VisOn;
}
window.onbeforeunload = leave;
window.onload = load;
</script>
</head>
<style>
body {background-color: lightyellow}
h1 {color:blue}
</style>
<body>
<form>
<br>
value is :
<script type="text/javascript">
document.write(VisOn)
</script>
</form>
<br>
</body>
</html>
答案1
得分: 0
你忘记初始化变量 VisOn
var VisOn = 0;
按照这样做应该可以正常工作。
更新:已添加可工作的 jsfiddle 链接
https://jsfiddle.net/qept46bo/
英文:
you forgot to initialize the variable VisOn
var VisOn = 0;
Do it like this and it should work.
UPDATE: Added the working jsfiddle
https://jsfiddle.net/qept46bo/
答案2
得分: 0
除了上面提到的缺失初始化之外,还没有添加可以检索其他用户打开页面数量的机制。
你的JavaScript仅在客户端上运行,这意味着你需要添加一些服务器通信来达到预期效果。
英文:
besides the missing initialization already mentioned above, there is no mechanism added, that can retrieve the amount of other people opening the page.
Your javascript is running ONLY on the client, meaning you need to add some server communication to have the intended effect.
专注分享java语言的经验与见解,让所有开发者获益!
评论