2016-12-21 76 views
0

所以我有,有一個元素現有的Click事件處理程序,我想刪除JavaScript事件

  • 添加第二 Click事件處理程序(Item.executeSelectClick),將防止第一 Click處理程序
  • 然後,如果用戶點擊繼續$( '#外的政策')。找到( '#C-模式,繼續')。單擊
  • 刪除我的第二個Click事件處理程序(Item.executeSelectClick)並繼續與原始的事件處理程序。
    • button.removeEventListener('click',Item.executeSelectClick); setTimeout(function(){$(button).click()},3000);

請注意,我沒有一個參考第一點擊處理程序,我將無法得到一個。

Item.executeSelectClick = function(event){ 
    var button = event.target; 

    $('#out-of-policy').find('#c-modal-proceed').click(function(){ 
     $('#out-of-policy').css('display', 'none'); 
     button.removeEventListener('click', Item.executeSelectClick); 
     setTimeout(function(){$(button).click()}, 3000); 
    }); 

    $('#out-of-policy').show(); 

    event.preventDefault(); 
    event.stopImmediatePropagation(); 
    return false; 
} 

目前正在發生的事情是第二事件處理程序不被刪除,當我點擊按鈕的setTimeout(函數(){$(按鈕)。點擊()},3000); 單擊事件處理程序繼續攔截請求。

+0

我能問的總體目標是什麼嗎?這看起來像是頁面和代碼之間非常奇怪的交互。 – ManBearPixel

+0

我認爲這實際上是我之前問過的一個問題的副本http://Manackoverflow.com/questions/33045624/turning-off-specific-click-event – zfrisch

+0

@ManBearPixel總體目標是攔截一個事件,我沒有控制並引入所需的用戶輸入以繼續。 –

回答

0

建立在previous SO answer之上,討論了JavaScript事件設置中的命名空間,並假設您正在使用jQuery(如您的問題所示),此代碼段應該對您的情況有用。在.target第一次單擊將停止違約事件的傳播,運行代碼,然後取出單擊事件處理程序,這是設置:

$('.target').on('click.stopDefault', function(event){ 
    event.preventDefault(); 
    event.stopImmediatePropagation(); 

    console.log('Your code executed here...'); 

    $('.target').off('click.stopDefault'); 

}); 
0

您可以隨時使用克隆做你的東西,離開了原來的按鈕,無論如何,你不想篡改它,直到需要時才隱藏它。

$(function() { 
 
    var $original = $('#original'); 
 
    var $dupe = $original.clone(false); 
 
    
 
    // just something that'll hold a response 
 
    var $response = $('#response').find('span'); 
 
    
 
    // position the clone with the original 
 
    $original.after($dupe); 
 
    // hide the original button 
 
    $original.hide(); 
 
    
 
    // assign the clone something to do 
 
    $dupe.on('click', function(e) { 
 
    e.preventDefault(); 
 
    // clone stuff here 
 
    $response.text('attack of the clone!'); 
 
    // when clone finished doing its thing, 
 
    // simply hide it and show the original button 
 
    $dupe.hide(); 
 
    $original.show(); 
 
    }); 
 
    
 
    // nothing here, say the original got clicked... 
 
    $original.on('click', function(e) { 
 
    e.preventDefault(); 
 
    $response.text('original clicked!'); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 

 
<a id="original" href="#">click me</a> 
 
<p id="response">response: <span></span> 
 
</p>