2013-06-24 2 views
-2

이 질문은 여러 번 있지만 다른 형태로되어 있습니다. 최상위 함수의 범위 내에서 selected 변수에 액세스하려고합니다 (alert은 현재 정의되지 않은 상태로 반환됩니다). return을 어떤 식 으로든 사용해야하는지 알고 있습니다. 미리 감사드립니다.JS 범위 : 변수에 액세스

$('#people_search_mobile').change(function() { 

    var selected; 

    $('li a', $('#suggestions')).bind('click.autocomplete',function(){ 
    selected = ($(this).text()); 
    }); 

    alert(selected); 

} 

답변

1

Meagar가 올바른지 : 당신이 값을 경고하려는 경우

, 당신은 li a 실제로 클릭 할 때 그렇게 할 필요가 그런 식으로 이벤트 처리기를 깨끗하게 유지합니다.

$('#people_search_mobile').change(function() { 

    var selected, myClickHandler; 

    myClickHandler = function(){ 
    selected = ($(this).text()); 
    alert(selected); 
    }; 

    $('li a', $('#suggestions')).bind('click.autocomplete', myClickHandler); 

} 

편집 : 또는 당신은 ... 다른 곳에서 다른 함수에

myClickHandler = function(){ 
    selected = ($(this).text()); 
    showMyAlert(selected); 
    }; 

... 

function showMyAlert(selected){ 
    alert(selected); 
} 
+0

감사합니다. 도움이됩니다. – keypulsations

4

이것은 의미가 없습니다. li a은 (는) alert이 발생했을 때 아직 클릭하지 않았습니다. alert항상undefined을 보여, 코드를 실행하지 않은 selected에 값을 할당하는 것이며, 를 실행하지 않을 수도 있습니다. 그러나 나는 때때로 다른 곳에서 함수를 작성하는 데 도움이 발견,

$('#people_search_mobile').change(function() { 

    var selected; 

    $('li a', $('#suggestions')).bind('click.autocomplete',function(){ 
    selected = ($(this).text()); 
    alert(selected); 
    }); 


} 
+0

확인 선택한 값을 전달하기를 원하지만 만약 내가 '외부의 다른 기능이 값을 전달하려면. 바인딩 ', 그 최선의 방법은 무엇입니까? – keypulsations

+0

@PaulOsetinsky 해당 코드를 이벤트 처리기 내부로 이동합니다. 여기서 'alert'를 배치했습니다. – meagar

관련 문제