Jquery:仅在新内容不同时替换内容

我有一个php文件,在ajax中每X秒调用一次以刷新内容。 这个php文件返回一个js文件,它必须改变div的html内容并产生效果。

但是,只有当新内容不同时,我才会想要更改此内容! 另外,我有一个div,即使它是相同的内容,它也会自动刷新效果!

我测试了这段代码:

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

但是这段代码不是跨浏览器……的确,我的data_insertion变量包含一些html内容。 并且每个浏览器都会插入它来更改attribut顺序等。这就是为什么,$(’#mydiv’)。html()永远不会等于data_insertion。

您可以使用附加到元素的结果的本地缓存。 在你的ajax回调中做类似的事情:

 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); }