【问题标题】:ClearInterval() not working anyone knows why?ClearInterval() 不工作有人知道为什么吗?
【发布时间】:2014-01-31 23:47:14
【问题描述】:

我正在通过此代码更新用户帖子:

var auto_refresh = setInterval(function() 
{
    $('.contenido-publicaciones')
        .load("refresh_p.php?search_user="+search_user).fadeIn();
}, 2500 ); //Which is working.

1:<div class="contenido-publicaciones">,所有来自 refresh.p.php 的 <div class="this-is-a-post"> div 每 2.5 秒加载一次。

2:我在每个 <div class="this-is-a-post"> 内部都有一个 textarea 标签,从 refresh_p.php 刷新。

3:<div class="contenido-publicaciones">刷新时,也会刷新textarea,阻止用户输入。

4:所有文本区域都有b_green类

当用户单击类为b_green 的文本区域时,我想clearInterval(auto_refresh),以便其他用户可以向该帖子发送评论。

我尝试了以下方法:

$(".b_green").click(function(){ clearInterval(auto_refresh); }); // 没用,<div class="contenido-publicaciones"> 继续刷新。

$("textarea").click(function(){ clearInterval(auto_refresh); }); // 仅当我单击页面顶部的文本区域以发送帖子时有效,但当我单击具有类 b_green 的文本区域时不起作用。

$(this).click(function(){ clearInterval(auto_refresh); }); //如果我点击 b_green textareas 就可以了,但是在用户每次点击页面时停止间隔,我只想在点击 b_green textareas 时停止。

我的代码有错误吗?任何帮助将不胜感激。

【问题讨论】:

标签: javascript php jquery html css


【解决方案1】:

点击不会触发,因为在您绑定它们时没有 textareas 或者后面的那些被替换为新的。这些新的文本区域没有附加 onclick 处理程序。

您可以执行以下任一操作:

  1. 将onclick="clearInterval(auto_refresh);" 添加到后端发送的文本区域的代码中,然后得到如下内容:

    <textarea onclick="clearInterval(auto_refresh);"></textarea>
    
  2. 使用on 将点击处理程序绑定到页面上保留的更高元素,如下所示:

    $(".contenido-publicaciones").on('click', 'textarea', function(){
        clearInterval(auto_refresh);
    });
    

【讨论】:

    【解决方案2】:

    据我了解,您加载的内容包含您尝试通过单击处理的所有节点。

    如果是这样。有一个问题。因为每次获得更新时,您都会丢失点击处理程序,因为 DOM 已经改变。 as + 你可能从以前的“无法访问”的处理程序这里有内存泄漏

    【讨论】:

    • 任何无法访问的代码都会被垃圾回收,javascript.info/tutorial/memory-leaks
    • 我建议你谷歌。如何使用设置的间隔和处理程序进行内存泄漏。你会很惊讶的。
    猜你喜欢
    • 2019-11-09
    • 2014-02-27
    • 1970-01-01
    • 1970-01-01
    • 2021-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多