jQuery:仅在新内容不同时才替换内容 [英] Jquery: replace content only if the new content is different

查看:115
本文介绍了jQuery:仅在新内容不同时才替换内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个php文件,它在Ajax中每隔X秒被调用一次以刷新内容.此php文件返回的js文件必须更改带有效果的div的html内容.

I have a php file which is called every X second in ajax to refresh a content. This php file return a js file wich must change the html content of a div with a effect.

但是,仅当新内容有所不同时,我才想更改此内容!否则,我有一个div,即使内容相同,它也会刷新效果!

But I would want to change this content only if the new is different! Else, I have a div which refresh itself with the effect even if it's the sames contents!

我用以下代码进行了测试:

I tested with this code:

if ($('#mydiv').html()!=data_insertion) $('#mydiv').fadeTo("fast", 0, function () {$(this).html(data_insertion).fadeTo("fast", 1)});

但是此代码不是跨浏览器的...确实,我的data_insertion变量包含一些html内容.每个浏览器都会插入它,更改属性顺序等.这就是为什么$('#mydiv').html()永远不等于data_insertion.

But this code isn't cross browser... Indeed, my data_insertion variable contains some html content. And each browser insert it changing the attribut order etc. That's why, $('#mydiv').html() is never equal to data_insertion.

推荐答案

您可以使用附加到元素的结果的本地缓存. 在您的ajax回调中,执行以下操作:

You can use a local cache of the result, attached to the element. In your ajax callback do something like:

if (jQuery.data($('#mydiv')[0], 'last_data_insertion') != data_insertion) {
    // Update DOM content
    $('#mydiv').fadeTo("fast", 0, function () {$(this).html(data_insertion).fadeTo("fast", 1)});

    // Reset the local cache
    jQuery.data($('#mydiv')[0], 'last_data_insertion', data_insertion);
}

这篇关于jQuery:仅在新内容不同时才替换内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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