问题
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