简体   繁体   English

我如何测试看是否 <DIV> 内容在显示之前已更改

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

Ive got a div with the id "responsecontainer" and I want to load a page. 我有一个id为“ responsecontainer”的div,我想加载一个页面。 If the contents of the DIV have changed then update the DIV otherwise just leave it the same. 如果DIV的内容已更改,请更新DIV,否则将其保持不变。

Here is my code, which doesnt work; 这是我的代码,不起作用;

<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>

This: 这个:

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

Should be this: 应该是这样的:

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

I wouldn't rely on .html() representations for string comparison. 我不会依赖.html()表示形式进行字符串比较。

The browser decides how the HTML string should be rendered, and the developer won't be able to have any control if the browser decides it should be displayed differently one time. 浏览器决定如何呈现HTML字符串,如果浏览器决定一次显示不同的HTML字符串,则开发人员将无法控制。

You should have a variable that is accessible to each interval invocation, and do a string comparison between the old and new responses. 您应该具有每个间隔调用都可以访问的变量,并在新旧响应之间进行字符串比较。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM