jQuery .trigger('click') inside interval function?

跟風遠走 提交于 2020-01-04 05:55:48

问题


This is a rephrased question from here. After some testing I isolated the problem, but have no clue on fixing it. No need to read the previous question, this is the simplified code:

THE PROBLEM -> trigger('click') executes, but the event doesn't trigger when inside looped (intervaled) function

$(document.ready(function(){
    var checkForConfirmation = function(){
        clearInterval(checkInterval);
        $("#anchorLink").trigger('click');
    }
    var checkInterval = setInterval(function(){checkForConfirmation()}, 5000);
});

The function is being called in intervals. When the proper response is replied, interval stops, and simulates the click on an anchor link.

In the html file there is an anchor link <a id="anchorLink" href="#hiddenDiv">Show</a>.
It points to the hidden div which has some content. I'm using Fancybox plugin to show the hidden div when the anchor link is clicked.

If I click on Show link fancybox shows, as expected.
If I get the response from the back-end, code executes as expected, but fancybox is not shown.
If I move $("#anchorLink").trigger('click'); outside the checkForConfirmation function, fancybox shows.
When I replace $("#anchorLink").trigger('click'); with $("#anchorLink").text('Im clicked'); the string shows in the <a id="ancoredLink"> tag.

This is the summary, I have tried it in different situations.
The problem is obviously in triggering the click event while in looping function. The $("#anchorLink") selector is accessible, it is triggering it correctly from everywhere else. Obviously there is a problem in triggering the mouse event inside looping function.

Any suggestions?


回答1:


Try:

$(document).ready(function(){
  // ...
});

instead of:

$(document.ready(function(){
  // ...
});


来源:https://stackoverflow.com/questions/5037454/jquery-triggerclick-inside-interval-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!