2014-07-02 78 views
-3

也許我只是看起來太近了,但我不明白爲什麼我沒有返回更新的變量。從on()函數返回變量 - jquery

的Javascript

var playlist_id="000"; 

$('nav').on("click", "a", function(){ 
    playlist_id = $(this).attr('rel'); 
}); 

console.log(playlist_id); //returns 000, instead of 111 

var playListURL = "http://gdata.youtube.com/feeds/api/playlists/"+playlist_id+"?v=2&alt=json&callback=?"; 

HTML

<li><a id="one" rel="000"><img src="images/season1.jpg" /></a></li> 
<li><a id="two" rel="111"><img src="images/season2.jpg" /></a></li> 
  • 修訂

我需要訪問日的範圍之外的PLAYLIST_ID e .on()函數。

+0

的console.log之前'是越來越執行on'單擊事件 – exexzian

+0

爲什麼它應該是什麼?您正在將'playlist_id'作爲事件回調的分配 –

+2

即使您不點擊「console.log」,您是否感到驚訝? :-D – zerkms

回答

4

我將通過解釋什麼時候運行來解決這個問題,注意評論。希望你會看到playlist_id總是全局訪問,你只是沒有正確地思考它的值何時設置。

var playlist_id="000";  //<-- I run first, setting playlist_id to '000' 
$('nav').on("click", "a", function(){ //<-- I run second, telling my browser that when navs are clicked, to run the code inside the function to set playlist ID 
    playlist_id = $(this).attr('rel'); //<-- I do not run until a nav is clicked. 
    //Any time after a nav is clicked, if you open up a debugger and check the value of the variable playlist_id, you will see it will have the correct value. 
}); 
console.log(playlist_id); //<-- I run third. 
          //Look at the two other statements that have run before me. 
          //What would you expect the value of playlist_id to be? Hint:000 

我增加了對的jsfiddle證明一勞永逸,該值是全局訪問。我保持你的代碼原樣,但每隔500毫秒,我正在將playlist_id的值寫入日誌。打開小提琴,觀看控制檯日誌,然後在兩個圖像上單擊。您會看到該值在您點擊時發生變化,並且可以全局訪問。 http://jsfiddle.net/T9YkH/

setInterval(function(){ 
    console.log(playlist_id); 
}, 500); 
+0

是的,這工作,但我希望覆蓋全局變量。 – JMP

0

.on()總是回報對象(或多個)它被調用,方便鏈接。在您的情況下,它會返回$('nav')

根據您發佈的代碼,變量playlist_id在點擊發生時得到分配。並且您正試圖在綁定click事件之後,但在它實際觸發之前將其記錄在控制檯中。

0

這些都沒有幫助,所以我回答了這個問題。

這應該刪除,因爲它不會幫助社區。

這就是我一直在尋找的解決方案:

var playlist_id="000"; 

    $('nav').on("click", "a", function(){ 
     playlist_id = $(this).attr('rel'); 
     onStart(playlist_id); 
    }); 

    onStart(playlist_id); 

    function onStart(playlist_id){ 
     var playListURL = "http://gdata.youtube.com/feeds/api/playlists/"+playlist_id+"?v=2&alt=json&callback=?"; 
} 
+0

我們是不是已經表明價值確實發生了變化,這正是您想要的嗎?但是,在發生點擊事件之前,您無法獲得新值。如果這就是你想要的,那是不可能的。 –

+0

確實......真的幫助那裏。 – JMP

+1

我再說一遍:由於您沒有提供任何上下文信息,我們無法真正提出替代解決方案。我們所能說的只是:價值確實發生了變化,您目前無法訪問它。從那裏你必須單獨繼續。 –