如何将三个事件绑定到Jquery或jJavascript中的同一函数?

问题描述 投票:0回答:3

谁能解释如何将三个事件绑定到同一函数?即,当以下事件发生时,应调用相同的函数。

  • 窗口卸载。
  • 按“ ESC”按钮时。
  • 点击“关闭”类。

我已通过以下方式编写了单击'.close'类的功能:

<script>
$(document).ready(function() {
    var start = new Date().getTime();
    var starttime = new Date(start);
    $(".close").click(function () {
        jwplayer('mediaplayer').stop();
        end = new Date().getTime();
        endtime = new Date(end);            
        $.ajax({ 
          url: "/courses/136",
          data: {'timeSpent': endtime - starttime},
        });
    });

  });
</script>

window.unload()和按ESC按钮应该发生相同的事情。有没有为此的Jquery方法。

javascript jquery keyboard-events jquery-events event-binding
3个回答
3
投票

创建一个负责处理事件的函数,然后您只需要将该函数传递给要执行的每个事件即可。

<script>
  $(document).ready(function() {
    var start = new Date().getTime();
    var starttime = new Date(start);

    var eventHandler = function (event) {
        jwplayer('mediaplayer').stop();
        end = new Date().getTime();
        endtime = new Date(end);            
        $.ajax({ 
          url: "/courses/136",
          data: {'timeSpent': endtime - starttime},
        });
    };

    $(".close").click(eventHandler);
    $(window).on("unload", eventHandler);
    $(document).on("keydown", function(e) {
        if (e.which == 27) {
            eventHandler(e);
        }
    });
  });
</script>

2
投票

您只需定义函数:

function handler() {
    jwplayer('mediaplayer').stop();
    end = new Date().getTime();
    endtime = new Date(end);            
    $.ajax({ 
      url: "/courses/136",
      data: {'timeSpent': endtime - starttime},
    });
}

...并将其绑定三遍;对于ESC键部分,您可能需要包装器:

$(".close").click(handler);
$(window).on("unload", handler);
$(document).on("keydown", function(e) { // Or whatever element is relevant
    if (e.which == 27) {
        handler.call(this, e);          // With the above, just `handler();` would work too
    }
});

0
投票

您传递给.click()之类的jQuery方法的函数不必是匿名的。您可以按名称引用函数。所以:

function yourFunction() {
   // do your jwplayer and ajax thing here
}

$(window).on("unload", yourFunction);
$(".close").click(yourFunction);
$(document).on("keyup", function(e) {
  if (e.which == 27)
    yourFunction();
});
© www.soinside.com 2019 - 2024. All rights reserved.