2017-01-08 4 views
-5

könnte jemand erklären, warum dieses Skript nicht funktioniert? Ich habe lange versucht, es herauszufinden, aber ich habe es nicht geschafft.Javascript - Anfänger Skript funktioniert nicht

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<!DOCTYPE html> 
 
<html> 
 
<head> 
 
    <script> 
 
     function Xyz() { 
 
      var x = 0; 
 
     } 
 

 
     function Switch() { 
 
      if (x == 0) { 
 
       document.body.style.backgroundColor = "black"; 
 
       x = 1; 
 
      } 
 
      else { 
 
       document.body.style.backgroundColor = "white"; 
 
       x = 0; 
 
      } 
 
     } 
 
    </script> 
 
</head> 
 
<body> 
 
    <button type="button" onclick="Switch()">Click me</button> 
 

 
</body> 
 
</html>

+0

Wer 'X' in Ihrer Funktion ist? –

+1

Inwiefern funktioniert es nicht? Welche Fehlermeldungen werden in Ihrer JavaScript-Konsole gemeldet (normalerweise "F12")? Was hast du von ihm erwartet? –

Antwort

0
if(x==0) 

Da x nicht existiert, wirft es einen Reference hier und bricht den Rest der Funktion.

Sie müssen zuerst x deklarieren.


Dieses:

function Xyz() 
{ 
var x=0; 
} 
  • Erzeugt eine Variable x die lokale ist auf die Funktion und
  • Ist sowieso nie genannt
0

Sie benötigen Variable x zu definieren. Ich habe das Heben in diesem Beispiel benutzt.

<!DOCTYPE html> 
 
<html> 
 
<head> 
 
<script> 
 
function Xyz() 
 
{ 
 
var x=0; 
 
} 
 

 
function Switch() 
 
{ 
 
if(x==0) 
 
{ 
 
document.body.style.backgroundColor="black"; 
 
x=1; 
 
} 
 
else 
 
{ 
 
document.body.style.backgroundColor="white"; 
 
x=0; 
 
} 
 
} 
 
    var x; 
 
</script> 
 
</head> 
 
<body> 
 
<button type="button"onclick="Switch()">Click me</button> 
 

 
</body> 
 
</html>

0

Problem ist, dass Sie eine Variable deklarieren müssen, bevor Sie sie verwenden.

Da Sie dieselbe Variable verwenden müssen, um sie mit jedem Klick zu aktualisieren, definieren Sie sie außerhalb der Funktion

<!DOCTYPE html> 
 
<html> 
 
<head> 
 
<script> 
 
var x = 0; 
 
function Xyz() 
 
{ 
 
var x=0; 
 
} 
 

 
function Switch() 
 
{ 
 
if(x==0) 
 
{ 
 
document.body.style.backgroundColor="black"; 
 
x=1; 
 
} 
 
else 
 
{ 
 
document.body.style.backgroundColor="white"; 
 
x=0; 
 
} 
 
} 
 
</script> 
 
</head> 
 
<body> 
 
<button type="button"onclick="Switch()">Click me</button> 
 

 
</body> 
 
</html>