【发布时间】: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