挂起jQuery中的默认事件 [英] Suspend Default Event in jQuery

查看:65
本文介绍了挂起jQuery中的默认事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试延迟jQuery脚本中的默认事件.上下文是我要在用户执行某些操作(主要是单击)几秒钟后向用户显示一条消息,然后触发默认操作.

I am trying to delay the default event or events in a jQuery script. The context is that I want to display a message to users when they perform certain actions (click primarily) for a few seconds before the default action fires.

伪代码: -用户点击链接/按钮/元素 -用户收到一条弹出消息,指出您正在离开网站" -消息在屏幕上保留X毫秒 -默认动作(也可以不是href链接)触发

Pseudo-code: - User clicks link/button/element - User gets a popup message stating 'You are leaving site' - Message remains on screen for X milliseconds - Default action (can be other than href link too) fires

到目前为止,我的尝试看起来像这样:

So far, my attempts look like this:

$(document).ready(function() {
    var orgE = $("a").click();
    $("a").click(function(event) {
        var orgEvent = event;
        event.preventDefault();
        // Do stuff
        doStuff(this);

        setTimeout(function() {
            // Hide message
            hideMessage();
            $(this).trigger(orgEvent);
        }, 1000);
    });
});

当然,这不能按预期工作,但可能会显示我正在尝试做的事情.

Of course, this doesn't work as expected, but may show what I'm trying to do.

我无法使用插件,因为这是一个无法在线访问的托管环境.

有什么想法吗?

推荐答案

我可能会做这样的事情.

I would probably do something like this.

$("a").click(function(event) {
   event.preventDefault();
   doStuff(this);
   var url = $(this).attr("href");

   setTimeout(function() {
      hideMessage();
      window.location = url;
   }, 1000);
});

我不确定是否可以从定时函数内部看到url.如果没有,您可能需要在点击处理程序之外声明它.

I'm not sure if url can be seen from inside the timed function. If not, you may need to declare it outside the click handler.

编辑:如果您需要通过定时功能触发事件,则可以使用类似于karim79建议的内容,尽管我会做一些更改.

If you need to trigger the event from the timed function, you could use something similar to what karim79 suggested, although I'd make a few changes.

$(document).ready(function() {
  var slept = false;
  $("a").click(function(event) {
    if(!slept) {
        event.preventDefault();
        doStuff(this);

        var $element = $(this);
        // allows us to access this object from inside the function

        setTimeout(function() {
          hideMessage();
          slept = true;
          $element.click(); //triggers the click event with slept = true
        }, 1000);
        // if we triggered the click event here, it would loop through
        // this function recursively until slept was false. we don't want that.
    } else {
        slept = false; //re-initialize
    }
  });
});

编辑:经过一些测试和研究,我不确定实际上是否有可能触发<a>元素的原始click事件.除<a>之外的任何其他元素似乎都有可能.

After some testing and research, I'm not sure that it's actually possible to trigger the original click event of an <a> element. It appears to be possible for any element other than <a>.

这篇关于挂起jQuery中的默认事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆