2015-07-22 75 views
-1

我是一個總的javascript noob,我只是試圖通過這個簡單的項目,我的方式blustickon。應該發生的事情是腳本只能在y運行時運行第二個IF語句,每次運行第二個IF語句時,它的意思是爲y的count加1,如果它運行ELIF,它意味着從y中減去一個計數。目標是讓您每次只能有3張「選定」的照片。我的y確實改變了,但是IF(y < = 3)似乎並沒有阻止程序運行。在此先感謝,傑克如果功能javascript不工作

<SCRIPT type="text/javascript"> 
    var y = 4; //this is a counter 

    function swapRoast() { //This defines the function 
      var x=document.images; //this automatically creates an array of all the images in the document starting with image0 and assigns them to variable'x' 

      if (y <= 3); { //this should check that y <= 3 before running 

      if (x[0].src.match('Roast_Vegetables.png')) //This tests if the source of image0 in the array matches the script 
      { 
      x[0].src=('Roast_Vegetables_Selected.png'); //If the source matches, then it is changed 
      y ++; //should add 1 to the y count 
      } 

      else if (x[0].src.match('Roast_Vegetables_Selected.png')) //If the source doesn't match, then it tests a different source 
      { 
      x[0].src=('Roast_Vegetables.png'); //If the different source matches, then the script operates in reverse to the original IF 
      y --; //should subtract 1 from the y count 
      } 
      } 
     } 

     function swapVege(obj) { 
      var x=document.images; 

      if (y <= 3); { 

      if (x[1].src.match('Vegetables.png')) 
      { 
      x[1].src=('Vegetables_Selected.png'); 
      y ++; 
      document.getElementById("demo").innerHTML = y; 
      } 

      else if (x[1].src.match('Vegetables_Selected.png')) 
      { 
      x[1].src=('Vegetables.png'); 
      y --; 
      document.getElementById("demo").innerHTML = y; 
      } 
      } 
     } 

回答

1

分號是不幸的,立即終止if塊。變化(在這兩個地方)

if (y <= 3); { 

喜歡的東西

if (y <= 3) { 
+0

當我這樣做時,圖像根本不會改變爲「選定」版本 編輯:剛剛意識到這是什麼原因造成這個問題:我有y開始在4 – jack

+0

@jack以前做過?你可以編輯你的問題,包括一個完整的和可重複的例子嗎?此外,請不要使用全局變量來計算* selected * items ...只是遍歷所有項目並計數。 –

+0

知道了所有的工作,謝謝你的提示。這樣一個簡單的錯誤,我不會再做! – jack

1

如果(Y < = 3); {

取出「;」這裏

+0

當我這樣做時,圖像根本不會更改爲「選定」版本。 編輯:剛剛意識到是什麼導致這個問題在這裏:我已經從4 – jack

+0

@jack開始,你有什麼建議? – zerkms

+0

知道了所有的工作,謝謝你的提示。這樣一個簡單的錯誤,我不會再做! – jack