【问题标题】:Timer function on ajax generated contentajax 生成内容的定时器功能
【发布时间】:2014-02-14 16:44:15
【问题描述】:

我有一个显示实时 Twitter 提要的网页。

内容是一组具有 mlink 类的链接。

如果我单击一个链接,它会使用在 OnClick 事件上触发的 jquery 工具提示来显示特定的推文详细信息 - 这非常有效。脚本 1

在 php 脚本上使用 Ajax 每隔几秒钟就会不断更新内容 - 这再次完美运行。脚本 2

我在页面上有第三个脚本,它与脚本 1 执行相同的操作,但它使用计时器而不是点击事件。同样,这对页面加载时加载的内容非常有效,但不适用于 ajax 生成的内容。脚本 3

我知道我必须使用委托而不是 $(document).ready 才能工作。但由于我的 JQuery 知识非常有限,我不知道该怎么做。任何帮助将不胜感激。

这是脚本 3

<script>
$(document).ready(function() {

setInterval(function() {

    //Get ids of all links with class mlink and insert into array
    var IDs = [];
    $(".mlink").each(function(){ IDs.push(this.id); });

    //Select random element from array
    var item = IDs[Math.floor(Math.random()*IDs.length)];

    //Get attributes of item
    var xid = $('#'+item).attr('xid');
    var yid = $('#'+item).attr('yid');
    var zid = $('#'+item).attr('zid');
    var tcon = $('#'+item).attr('tcon');
    var imgcon = $('#'+item).attr('imgcon');
    var dtscon = $('#'+item).attr('dtscon');

    //Generate HTML
    var htmlstr = '';
    var htmlstr = htmlstr+'<div style="display: none; max-width: 600px; position: absolute;" class="ttx" id="'+xid+'">';
    var htmlstr = htmlstr+'<div class="row">';
    var htmlstr = htmlstr+'<div class="large-3 columns xicon" id="'+yid+'">';
    var htmlstr = htmlstr+'<img src="'+imgcon+'" />';
    var htmlstr = htmlstr+'</div>';
    var htmlstr = htmlstr+'<div class="large-9 columns xtcon" id="'+zid+'">';
    var htmlstr = htmlstr+'<h2>'+tcon+'</h2>';
    var htmlstr = htmlstr+'</div>';
    var htmlstr = htmlstr+'</div>';
    var htmlstr = htmlstr+'</div>';

    //Close any open tooltip
    $('.ttx').remove();

    //Append Generated content to body
    $('body').append(htmlstr);

    //Position Generated Content
    $('#'+xid).center();
    $(window).resize(function(){
        $('#'+xid).center();
    });

    //Show Generated Content
    $('#'+xid).toggle(function(){
        $('#'+zid).fadeIn('slow');
    });

    //Remove tooltip
    setInterval(function(){
        $('.ttx').remove();
    }, 1000 * 60 * 0.2);
}, 1000 * 60 * 0.1); 
});

//Centering function
jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) +
    $(window).scrollTop()) + "px");
    this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) +
    $(window).scrollLeft()) + "px");
    return this;
}
</script>

【问题讨论】:

  • 请添加 jsfiddle 或 plnkr 演示以显示您的代码

标签: javascript jquery ajax


【解决方案1】:

确保您的事件附加在不会被 Ajax 生成的内容替换的元素上,或者确保在通过 Ajax 生成内容后(重新)附加这些事件。

【讨论】:

  • 是的。我明白那个。我的问题是我的事件只是时间而不是“点击”之类的东西。我的具体问题是如何编写一个使用 eventType 时间的委托
  • 嗯很难说.. 代码看起来不错,我猜第二个 setInterval 应该是 setTimeout;您需要调试.. 检查您生成的数组 ID 的内容是否包含新项目。
猜你喜欢
  • 2017-05-08
  • 1970-01-01
  • 2010-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-25
  • 2014-12-06
相关资源
最近更新 更多