Does anyone know what typo I made, because my editor, and I can't seem to make it work

number=5;
switch (number) {
    case 5:
        box.onclick = function1;
        break;
    case 50:
        box.onclick = function2;
        break;
}

I've also tried doing it in switch.

有帮助吗?

解决方案 3

With this code:

number=5;
switch (number) {
    case 5:
        box.onclick = function1;
        break;
    case 50:
        box.onclick = function2;
        break;
}

case 50 will never be hit because you set number to 5 before entering the switch block. Therefore box onclick will never equal function2. Therefore, when you click the box, function2 will not be run. Is this really an accurate representation of your actual code, or is it a simplification that has left out important information?

其他提示

Try not using the reserved word var as a variable name:

var x=5;
    if (x==5){
        box.onclick = function1;
    }
    if(x==50){
        box.onclick = function2;
    }

var is the reserved word to create variables. You can't use it as a name. This is the correct syntax:

var x = 5;

if (x == 5) {
    box.onclick = function1;
}

if (x == 50) {
    box.onclick = function2;
}

You can't use reserved JavaScript words for declaring variables.

Try to replace var=5 to myVar=5 for example.

var myVar = 5;

if (myVar ==5){
    box.onclick = function1;
}
if(myVar ==50){
    box.onclick = function2;
}

Also, check out this reference: JavaScript Reserved Words

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top