如何创建在一定延迟后单击特定URL的JavaScript

How to create a JavaScript that clicks a particular URL after a certain amount of delay?

本文关键字:延迟 单击 URL JavaScript 何创建 创建      更新时间:2023-09-26

我想创建一个JavaScript,在一定的延迟后点击特定的链接,例如在HTML页面上点击10秒。

你能给我提供JavaScript吗?我在谷歌上搜索后才找到一个特定的链接,但没有延迟。

你能帮我吗?

谢谢。

包含此方法(根据需要):

function fireEvent(element,event) { 
   if (document.createEvent) { 
       // dispatch for firefox + others 
       var evt = document.createEvent("HTMLEvents"); 
       evt.initEvent(event, true, true ); // event type,bubbling,cancelable 
       return !element.dispatchEvent(evt); 
   } else { 
       // dispatch for IE 
       var evt = document.createEventObject(); 
       return element.fireEvent('on'+event,evt) 
   } 
} 

然后称之为:

window.setTimeout(function() { 
    var e = document.getElementById('yourLinkId');
    if(e) fireEvent(e, 'click');
}, 10000); 
window.setTimeout(function() {
    window.location = "http://your_url_here.com";
}, 10000);

第二个参数是以毫秒为单位的时间。所以10000毫秒就是10秒。

如果您需要像本网站上显示的那样的延迟(请参阅页面左下角的"Testimonials"容器),请使用以下jQuery代码。

(function($){
$(document).ready(function(){
    var el = $("#testimonial"); //The id of the container. It may be a `<div>`
    if (el){
    RotateTestimonial();
    setInterval(RotateTestimonial, 20000);
    }
});
function RotateTestimonial(){
    var pageUrl = "RandomTestimonial.jsp"  //The page where the request goes.
    $.ajax({
            type: "GET",
            url: pageUrl,
            cache:false,
            success: function(msg) {                   
                $("#testimonial").slideUp('slow').fadeOut(3000, function (){
                    var el = $("#testimonial"); 
                    el.html(msg);
                    el.slideDown('slow').fadeIn('slow');
                });
            }
    });
}
})(jQuery)