2016-08-12 6 views
1

다른 조건으로 내 확인 조건을 트리거 할 수 있습니까?Javascript : 다른 함수에서 true를 반환하는 경우 트리거

myphp.php

<input type="button" id="button1" class"button2"> 

<script> 
$('#button1').on('click', function(){ 
if(confirm("Are you sure?")){ 
    //my stuff 
}else{ 
    return false; 
} 
}); 

$('.button2).on('click', function(){ 
    //if the confirm condition from first function return true 
    //i need to fire here as well without doing another if(confirm) 
}); 
</script> 
+1

'경우 (TRUE) {$ ('단추 2.) .click()}' –

+2

@u_mulder : 그 방법은 유지 보수가 어려운 스파게티있다. :-) –

+2

두 이벤트 핸들러에서 모두 호출 할 수있는 다른 명명 된 함수는 어떻습니까? – adeneo

답변

5

나는 당신이 두 곳이 호출 할 수 있습니다 당신이 함수에 두 곳에서 사용할 논리 넣어 코드를 모듈화 제안 :

// The function doing the thing 
function doTheThing(/*...receive arguments here if needed...*/) { 
    // ... 
} 
$('#button1').on('click', function(){ 
    if(confirm("Are you sure?")){ 
    doTheThing(/*...pass arguments here if needed...*/); 
    }else{ 
    return false; 
    } 
}); 

$('.button2').on('click', function(){ 
    //if the confirm condition from first function return true 
    //i need to fire here as well without doing another if(confirm) 
    doTheThing(/*...pass arguments here if needed...*/); 
}); 

사이드 노트 : 스크립트의 최상위 레벨에 표시했습니다. 아직 질문이 없으신 분이라면 모두을 제출하시는 것이 좋습니다. 전역을 방지하기 위해에 즉시-호출 범위 지정 기능의 송시 :

(function() { 
    // The function doing the thing 
    function doTheThing(/*...receive arguments here if needed...*/) { 
    // ... 
    } 
    $('#button1').on('click', function(){ 
    if(confirm("Are you sure?")){ 
     doTheThing(/*...pass arguments here if needed...*/); 
    }else{ 
     return false; 
    } 
    }); 

    $('.button2').on('click', function(){ 
    //if the confirm condition from first function return true 
    //i need to fire here as well without doing another if(confirm) 
    doTheThing(/*...pass arguments here if needed...*/); 
    }); 
})(); 
관련 문제