2015-11-03 58 views
0

我有一個共享的jQuery函數,檢查一個RadioButton選擇:如果選擇1,它隱藏一個跨度,否則它顯示它。從jQuery同時啓動/更改相同的RadioButton設置功能

這個共享函數在啓動時和在Change上被調用,因爲在啓動時它需要做同樣的事情。啓動工作,但參考的onChange不工作:

JS_OBJ = { 

    toggleTier : function() { 

     if ($('input[name="tier"]:checked').val() == 'Y_YES') 
     { 
      $('#tierSpan').hide(); 
     } 
     else 
     { 
      $('#tierSpan').show(); 
     }  

    }, 

    // this is called from document.onReady - it comes here, OK 
    onReady : function() {  

     // on startup, toggle Tier - works OK 
     this.toggleTier(); 

     // Also link the radio button Change to this shared function 
     $('input[name="tier"]:radio').change(function() { 
      alert('About to enter toggle...'); 
      // NEVER COMES HERE - Object doesn't support this property or method 
      this.toggleTier(); 
     }); 

    } 

}; 

回答

1

裏面的變化事件,並不是指當前JS_OBJ,它指的是當前事件目標代替。你想明確地保存你的參考這個,所以你可以在事件內部使用它。

實施例:

onReady : function() {  

    var me = this; 
    me.toggleTier(); 

    // Also link the radio button Change to this shared function 
    $('input[name="tier"]:radio').change(function() { 
     me.toggleTier(); 
    }); 

} 
2

this被變更值,因爲它是通過直通的不同的區域。當它第一次實例,它具有良好的價值,但單選按鈕:變化有不同的this

我能夠改變它得到它的工作:

$('input[name="tier"]:radio').change(function() { 
     alert('About to enter toggle...'); 
     self; //closure 
     toggleTier(); 
    }); 

看到這一點:What underlies this JavaScript idiom: var self = this?

相關問題