Home > Article > Web Front-end > js simulate click event
After the page is loaded, we often encounter linkage problems. At this time, it is necessary to automatically trigger the first click event after the page is loaded so that subsequent linkages can be displayed on the web page.
You can use the
trigger method in js
$("selector").trigger("click");
For example, in my code, I first added a click event to the li in the ul and then simulated triggering the event.
$(".place-classify ul").on("click","li",function(){ var placeName = $(this).html(); createPlaceContent(placeName) ; }); $(".place-classify ul li:first-child").trigger('click');
But sometimes the simulation event is not triggered. Generally, you may encounter two problems:
The simulation click event is written in front of the click event.
Some people think that this is triggered after the page is loaded, especially if it is written in $(function(){});
, it is rendered first and then triggered, but when a page is opened, it is rendered first. The elements of the entire page, not the js code, will still be executed one by one. If the simulated click is written in the front, it will be triggered first and then declared, so it will have no effect. Just move it to the back of the click event. .
The click event has been moved to the back but still not triggered, so it may be due to asynchronous loading. Since your web page is loaded asynchronously, it will happen because the data has not been processed yet. Click event, in the same way, the click event is triggered before the dynamically generated elements are generated. The solution is to change the ajax request to a synchronous request. $.ajax({ <br>
url:url, <br>
Data:data, <br>
async:false, <br>
Success:function(result){ <br>
handle(result); <br>
}, <br>
Error:function(result){ <br>
alert("Failed to obtain data"); <br>
} } <br>
});
The above is the detailed content of js simulate click event. For more information, please follow other related articles on the PHP Chinese website!