clearInterval包含setInterval的方法之外 [英] clearInterval outside of method containing setInterval

查看:104
本文介绍了clearInterval包含setInterval的方法之外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可以在同一页面上多次调用的消息传递功能。每次调用时,屏幕顶部都会显示一条新消息,并且具有由递增全局设置的唯一ID。

I have a messaging function that can be called several times on the same page. Each time it's called, a new message appears at the top of the screen and has a unique ID set by an incrementing global.

该功能的一般概念如下:

The general idea of the function is below:

var messageTimer = function(msgid, duration) {
  ...
  var interval = setInterval(
    function() {
    ...
    },
    duration
  )
};

在上面的代码中,创建了一条新消息并应用了一个计时器。如果计时器用完,消息将消失。但是,如果在关闭按钮以外的任何地方单击该消息,则计时器应该停止并且消息应该保持到手动关闭。

In the code above, a new message is created and a timer applied. If the timer runs out, the message disappears. However, if the message is clicked on anywhere except the close button, the timer should stop and the message should stay until manually closed.

如何找到间隔ID单击消息框?可能还有3个其他盒子同时打开。

How do I find the interval ID of the message box clicked? There could be 3 other boxes simultaneously open.

$('body').on('click', '.msg', function() {

});

由于我只有一个类来触发点击,我认为唯一可行的方法是找到这是为消息框的ID设置一个附加字段?但是这个方法似乎没必要也很麻烦。

Since I only have a class to trigger the click by I'm thinking the only possible way to find this is to set an additional field to the ID of the message box? However this method seems unnecessary and messy.

推荐答案

我会在邮件上设置一个数据属性来存储间隔ID:

I would set a data property on the message which stores the interval ID:

var messageTimer = function(msgid, duration) {
  ...
  var interval = setInterval(
    function() {
    ...
    },
    duration
  );
  $("#" + msgid).data("i", interval);
};

然后回想一下你的消息内容:

Then recall it onclick of your message thingies:

$('body').on('click', '.msg', function() {
    clearInterval(parseInt($(this).data("i"), 10));
});

这篇关于clearInterval包含setInterval的方法之外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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