在显示 <DIV> 内容之前,如何对其进行测试以查看是否已更改

How do I test to see if <DIV> contents have changed before displaying them

本文关键字:测试 是否 DIV 显示      更新时间:2023-09-26

我得到了一个id为"responsecontainer"的div,我想加载一个页面。 如果 DIV 的内容已更改,请更新 DIV,否则只需保持原样。

这是我的代码,它不起作用;

<script>
$(document).ready(function () {
    $("#responsecontainer").load("qr.asp");
    var refreshId = setInterval(function () {
        $.get("qr.asp?randval=" + Math.random(), function (result) {
            var newContent = $('.result').html(result);
            if (newContent != $("#responsecontainer")) {
                $("#responsecontainer").html(result);
            };
        });
    }, 5000);
    $.ajaxSetup({
        cache: false
    });
});
</script>

这个:

if (newContent != $("#responsecontainer")) {

应该是这样的:

if (newContent != $("#responsecontainer").html()) {

我不会依赖.html()表示进行字符串比较。

浏览器决定 HTML 字符串应如何呈现,如果浏览器决定应以不同的方式显示一次,开发人员将无法控制它。

您应该有一个可供每个间隔调用访问的变量,并在旧响应和新响应之间进行字符串比较。

$(document).ready(function () {
    var prev_response;
    $("#responsecontainer").load("qr.asp", function(resp) {
        prev_response = resp;
    });
    var refreshId = setInterval(function () {
        $.get("qr.asp?randval=" + Math.random(), function (result) {
            if (prev_response !== result) {
                prev_response = result;
                $("#responsecontainer").html(result);
            }
        });
    }, 5000);
    $.ajaxSetup({
        cache: false
    });
});