Jquery单击事件未在超时函数中触发

时间:2015-07-02 20:24:57

标签: javascript jquery html

我希望在一个按钮变为可见时触发点击事件。由于某些原因,此按钮大约需要1秒钟才能在页面中显示。因此,当按钮出现时触发点击时,此功能会超时以检测event.I尝试但由于某种原因没有触发点击事件,按钮的外观检测是正确的,只有点击事件不起作用。这些是代码:

< cta'是按钮ID。

$(function checkBotaoApareceu(){
  console.log('teste');
  if($('#cta').is(':visible')){
    setTimeout(function(){
      $('#cta').click();
      console.log('click');
    }, 2000);
    return;
  }                        
  setTimeout( checkBotaoApareceu, 10 );
});

这是按钮的单击事件处理程序

$('#cta').click(function(event){
    event.stopPropagation();
    $('#cta').hide();
    blocoAmarelo = $('div .bloco-amarelo');
    $("#the_lights").css('height',$(document).height());
    $("#the_lights").css('display','block');
    $("#the_lights").fadeTo(1000,0.8);
    blocoAmarelo.show();
    blocoAmarelo.click(function(event){
        event.stopPropagation();
    });
});

$('html').click(function() {
    if(document.getElementById("the_lights").style.display === 'block'){
        document.getElementById("the_lights").style.display="none";
    }
});

注意:这里需要stopPropagation调用以保留一些div样式。

1 个答案:

答案 0 :(得分:0)

我仍然不知道导致错误的原因。但经过一些研究后,这个解决方案对我有用。

function eventFire(el, etype){
    if (el.fireEvent) {
      el.fireEvent('on' + etype);
    } else {
      var evObj = document.createEvent('Events');
      evObj.initEvent(etype, true, false);
      el.dispatchEvent(evObj);
    }
}

$(function(){
    var id = setInterval(function (){
        if ($('#cta').is(':visible')) {
            eventFire(document.getElementById('cta'),'click');                
            clearInterval(id);
        }
    }, 100);
});