js simulate click event

一个新手
Release: 2017-09-25 09:53:57
Original
5133 people have browsed it

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");
Copy after login

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');
Copy after login

But sometimes the simulation event is not triggered. Generally, you may encounter two problems:

  1. 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. .

  2. 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({
    url:url,
    Data:data,
    async:false,
    Success:function(result){
    handle(result);
    },
    Error:function(result){
    alert("Failed to obtain data");
    } }
    });

The above is the detailed content of js simulate click event. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!