2013-08-03 78 views
0

我陷入讓newGame函數運行,我不知道什麼是阻止它。Javascript麻煩傳遞選擇框值到對象參數

我有了3個級別選擇框,但每次我運行的達到了所選的水平newGame功能,它總是返回1的水平,甚至當我與價值的選擇框3

我不明白爲什麼這不起作用?最令人發狂的部分是我之前有這個工作,但不知怎的,我做了一些阻止它工作的東西。任何幫助,我感激!我也對代碼結構提出了一般批評。 謝謝!

$(document).ready(function(){ 

    (function(){ 

     var levelSelected = $('.gameLevel :selected'), 
      newGameSelected = $('.start'); 


     newGameSelected.on('click', function() { abc.newGame(); }) 

     var abc = { 

      level : levelSelected.val(), 

      abcArray : ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p'], 

      createLevel : function(){ 
       console.log('test'); 
      }, 

      newGame : function(){ 
       var level = this.level; 
       console.log('Doin level #: ' + level); 
      } 


     } 


    })(); 

    }) 
+1

你的腳本看起來有效,但我們可以看到你的HTML爲清楚起見? – theftprevention

回答

0

的問題是,你只得到了$('.gameLevel :selected')時,頁面加載。當您更改選擇並點擊.start時,此選項未刷新。要解決這個問題,您每次點擊.start時都必須重新獲得$('.gameLevel :selected').val()。像這樣:

$(document).ready(function(){  
    (function(){ 
     var newGameSelected = $('.start'); 
     newGameSelected.on('click', function() { 
         abc.level = $('.gameLevel :selected').val(); 
         abc.newGame(); 
     }) 
     var abc = { 
      abcArray : ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p'], 
      createLevel : function(){ 
       console.log('test'); 
      }, 
      newGame : function(){ 
       var level = this.level; 
       console.log('Doin level #: ' + level); 
      } 
     } 
    })(); 

});

或者

$(document).ready(function(){  
     (function(){ 
      var newGameSelected = $('.start'); 
      newGameSelected.on('click', function() { 
          abc.newGame($('.gameLevel :selected').val()); 
      }) 
      var abc = { 
       abcArray : ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p'], 
       createLevel : function(){ 
        console.log('test'); 
       }, 
       newGame : function (level){ 
        console.log('Doin level #: ' + level); 
       } 
      } 
     })(); 
    }); 
0

地方這條線

var levelSelected = $('.gameLevel :selected') 

newGame : function(){ 
    var levelSelected = $('.gameLevel :selected'); 
    var level =levelSelected.val(); 
    console.log('Doin level #: ' + level); 
}