简体   繁体   English

setTimeout与功能

[英]setTimeout with function

I'm trying to create a bookmarklet to open links with specific text, but I'm facing a problem with the setTimeout portion ... 我正在尝试创建一个书签以打开具有特定文本的链接,但是我遇到了setTimeout部分的问题...

javascript:(function(){
    function clickLink(link) {
        if (document.createEvent) {
            var event=document.createEvent("MouseEvents"); 
            event.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            link.dispatchEvent(event);
        } else if (link.fireEvent) {
            link.fireEvent("onclick");
        }
    } 

    l=document.links;
    for(var i=0;i<l.length;++i) {
        var lL=l[i].innerHTML.toLowerCase(); 
        if(lL.indexOf("click here")!=-1 || lL.indexOf("how")!=-1) 
             setTimeout(function() {clickLink(l[i]) }, 1000);
        }
    }; 
})();

If I try setTimeout(clickLink(l[i]), 1000); 如果我尝试setTimeout(clickLink(l[i]), 1000); , then it works, but it runs immediately rather than waiting for the timeout! ,那么它可以工作,但是它可以立即运行,而不是等待超时!

Also want to know one more thing that clicking links this way will fire mousedown/mouseup event? 还想知道另一件事,以这种方式单击链接会触发mousedown / mouseup事件吗? If not then how can I programmatically click links which will also fire mousedown/mouseup events? 如果没有,那么我如何以编程方式单击也会触发mousedown / mouseup事件的链接?

You're coming across the usual "loop variable in a lambda" problem: by the time the timeout is done, i will be past the end of document.links and l[i] will be undefined . 您遇到了常见的“ lambda中的循环变量”问题:到超时完成时, i将超过document.links的末尾,而l[i]将是undefined You could just wrap that part in a(nother) function: 您可以将该部分包装在(另一个)函数中:

(function(item) {
    setTimeout(function() { clickLink(item); }, 1000);
})(l[i]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM