1

有这段令人惊叹的代码,它运行得很好,但问题是我总是得到带有相同消息的新 DIV,我如何更改它以使其出现在同一个地方?msgsrv.php 文件只是一个echo "Test Message";,但它会从 MySQL 数据库中提取数据。所以我得到的是测试消息,然后是下一行的测试消息,我想让新消息替换旧消息。

<html>
<head>
    <title>Auction</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript" charset="utf-8"></script>

    <style type="text/css" media="screen">
      body{ background:#000;color:#fff;font-size:.9em; }
      .msg{ background:#aaa;padding:.2em; border-bottom:1px #000 solid}
      .old{ background-color:#246499;}
      .new{ background-color:#3B9957;}
    .error{ background-color:#992E36;}
    </style>

    <script type="text/javascript" charset="utf-8">
    function addmsg(type, msg){
        /* Simple helper to add a div.
        type is the name of a CSS class (old/new/error).
        msg is the contents of the div */
        $("#messages").append(
            "<div class='msg "+ type +"'>"+ msg +"</div>"
        );
    }

    function waitForMsg(){
        /* This requests the url "msgsrv.php"
        When it complete (or errors)*/
        $.ajax({
            type: "GET",
            url: "msgsrv.php",

            async: true, /* If set to non-async, browser shows page as "Loading.."*/
            cache: false,
            timeout:50000, /* Timeout in ms */

            success: function(data){ /* called when request to barge.php completes */
                addmsg("new", data); /* Add response to a .msg div (with the "new" class)*/
                setTimeout(
                    waitForMsg, /* Request next message */
                    1000 /* ..after 1 seconds */
                );
            },
            error: function(XMLHttpRequest, textStatus, errorThrown){
                addmsg("error", textStatus + " (" + errorThrown + ")");
                setTimeout(
                    waitForMsg, /* Try again after.. */
                    15000); /* milliseconds (15seconds) */
            }
        });
    };

    $(document).ready(function(){
        waitForMsg(); /* Start the inital request */
    });
    </script>
</head>
<body>
    <div id="messages">
        <div class="msg old">
            Last Bid is:
        </div>
    </div>
</body>
</html>
4

1 回答 1

4

正如它所说,“追加”会将内容附加到元素,而 .html() 将更改元素的整个内部 html 并替换为您设置的内容。

代替

$("#messages").append(
        "<div class='msg "+ type +"'>"+ msg +"</div>"
    );

和:

$("#messages").html(
        "<div class='msg "+ type +"'>"+ msg +"</div>"
    );
于 2013-06-22T14:29:36.537 回答