2016-08-30 26 views
0

觸發方法調用的事件我想在JavaScript中檢測觸發點擊事件,我的代碼是如何檢測jQuery的

$(".my_button").click(function(){ 

    // if event fired form .trigger() method from other method or event then do something 

    // actuall code for click event is here 
}) 

..... 
..... 

$('.other_first_button').click(function(){ 
    // code of other first button 
    $(".my_button").trigger('click'); 
}); 

..... 
..... 

$('.other_second_button').click(function(){ 
    // code of other second button 
    $(".my_button").trigger('click'); 
}); 

注:我想使用jQuery trigger()方法標識$(".my_button").click()點擊事件呼叫。

提前感謝您的時間。

+5

你可以通過額外的數據到事件處理程序,請參見[商務部](http://api.jquery.com/trigger/) –

+0

我抓到你了,感謝@ A.Wolff –

+0

需要注意的是,你可以檢查'event.isTrigger',但這不是公共支持:https://github.com/jquery/api.jquery.com/issues/319(編輯:順便說一句主要開發者建議檢查'event.originalEvent',但恕我直言更好的辦法是在處理它時,使用'$ .fn.trigger()'方法將參數傳遞給事件處理函數)https://jsfiddle.net/vk1e3sp0/1 –

回答

1

我的按鈕將參數傳遞到觸發點擊事件作爲

$(".my_button").trigger('click', ['btn2']); 

收到它的點擊事件作爲

$(".my_button").click(function(e, p2){ 

不會檢查P2未定義或有一定的價值,如果它有它一直採用trigger()事件

$(".my_button").click(function(e, p1){ 
 

 
    // if event fired form .trigger() method from other method or event then do something 
 
    if(p1 != undefined) 
 
\t alert('triggered from ' + p1); 
 
    // actuall code for click event is here 
 
}) 
 

 

 
$('.other_first_button').click(function(){ 
 
    // code of other first button 
 
    $(".my_button").trigger('click', ['btn1']); 
 
}); 
 

 

 
$('.other_second_button').click(function(){ 
 
    // code of other second button 
 
    $(".my_button").trigger('click', ['btn2']); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<button class="other_first_button"> 
 
First 
 
</button> 
 
<button class="other_second_button"> 
 
Second 
 
</button> 
 
<button class="my_button"> 
 
mybtn 
 
</button>

觸發

JSFIDDLE

+0

謝謝......在'$('。my_button')。click(function(p1,p2){...})'那麼'p1'是代表什麼?而'p2'總是數組或每個單獨的參數? –

+0

你現在編輯的代碼更清晰了。 p1是事件參數,p2是自定義發送參數,很樂意提供幫助 –