2013-07-04 21 views
0

我有這個功能定義如何調用從jQuery的按鍵事件js函數

function updateMapMarker(inputValue) 
{ 
    geocoder.geocode({'address': inputValue}, function(results, status) 
    { 
     if (status == google.maps.GeocoderStatus.OK) 
     { 
      if (results[0]) 
      { 
       placeMarker(results[0].geometry.location); 
      } 
      else 
      { 
       alert('No results found'); 
      } 
     } 
     else 
     { 
      alert('Geocoder failed due to: ' + status); 
     } 
    }); 
} 

我增加了一個按鍵事件到這樣的輸入:

$('#tutor_singin_address').keypress(function (e) 
{ 
    if(e.keyCode==13) 
    { 
     updateMapMarker($('#tutor_singin_address').val()); 
    } 
}); 

但控制檯拋出此錯誤:

Uncaught ReferenceError: updateMapMarker is not defined 

我該如何調用我的js函數?

+1

函數是否在事件處理函數內可訪問的作用域中定義? –

+0

拼寫看起來正確,但仔細檢查拼寫和大小寫。 – Xaisoft

+0

[似乎在這裏工作](http://jsfiddle.net/hungerpain/muMK6/)..你的範圍一定有問題。如果函數'updateMapMarker'在一個單獨的js文件中,確保在keypress'方法加載之前加載該文件 – krishgopinath

回答

0

最簡單的方法是定義一個附加功能,作爲事件處理程序:

function keyPressHandler(e) { 
    if (e.keyCode == 13) { 
     updateMapMarker($('#tutor_singin_address')); 
    } 
} 

然後只是附加新功能的事件處理程序:

$('#tutor_singin_address').keypress(keyPressHandler); 

我相信你方式並不是因爲JavaScript處理範圍和this關鍵字的棘手方式,但我並沒有自己確認。給我的方式一槍!