문제

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