2016-12-21 77 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>