简体   繁体   English

“开关”中的功能不起作用

[英]Functions in “switch” doesn't work

I have the javascript stated bellow. 我有下面的javascript声明。 I need to execute some functions instead of alert(), but it doesn't work... I need to include document.getElementById("").innerHTML="" function. 我需要执行一些函数而不是alert(),但它不起作用......我需要包含document.getElementById(“”)。innerHTML =“”函数。 I'm not very experienced in js and I will be very grateful if somebody will explain how to do that and where is a problem. 我对js不是很有经验,如果有人会解释如何做到这一点以及问题出在哪里,我将非常感激。

window.onload = function locationHashChanged() {
    var hashx = location.hash;
    switch (hashx) {
       case '#basketball':
           alert('1');
           break;
       case '#football':
           alert('2');
           break;
       default:
           alert('3');
    }
    window.onhashchange = locationHashChanged;
}

Don't add a function name to the assignment of window.onload . 不要在window.onload的赋值中添加函数名。

You need to assign an anonymous function instead, such as 您需要指定anonymous function ,例如

window.onload = function(){
  // stuff
}

The most likely problem here is that you're defining window.onload after the load event has taken place, which means that your handler is not being called. 这里最可能的问题是你在load事件发生定义了window.onload ,这意味着你的处理程序没有被调用。 Either that, or some other code is overwriting your handler. 要么,或者其他一些代码都会覆盖你的处理程序。

You don't need to wait until the window 's load event for adding a hashChange event handler, so just use: 不需要等到window的Load事件添加hashChange事件处理程序,所以只需使用:

window.onhashchange = function() {
    var hashx = location.hash;
    switch (hashx) {
       case '#basketball':
           alert('1');
           break;
       case '#football':
           alert('2');
           break;
       default:
           alert('3');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM