Javascript - 如何动态添加新div并将数据附加到它

时间:2016-08-06 10:34:40

标签: javascript jquery append

我在SignalR的基本示例中工作 - 这是我的代码:

<!DOCTYPE html>
<html>
<head>
    <title>SignalR Simple Chat</title>
    <style type="text/css">
        .container {
            background-color: #99CCFF;
            border: thick solid #808080;
            padding: 20px;
            margin: 20px;
        }
    </style>

    <style type="text/css">
        .box {
            background-color: #0000ff;
            border: thick solid #008000;
            padding: 20px;
            margin: 20px;
        }
    </style>


</head>
<body>
<div class="container">
    <input type="text" id="message"/>
    <input type="button" id="sendmessage" value="Send"/>
    <input type="hidden" id="displayname" />
</div>

<div class="box" id="box1">
</div>


<!--Script references. -->
    <!--Reference the jQuery library. -->
    <script src="Scripts/jquery-1.6.4.min.js" "></script>
    <!--Reference the SignalR library. -->
    <script src="/Scripts/jquery.signalR-2.0.0.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="/signalr/hubs"></script>
    <!--Add script to update the page and send messages.-->
    <script type="text/javascript">
        $(function () {
            // Declare a proxy to reference the hub.
            var chat = $.connection.chatHub;
            // Create a function that the hub can call to broadcast messages.
            chat.client.broadcastMessage = function (name, message) {
                // Html encode display name and message.
                var encodedName = $('<div />').text(name).html();
                var encodedMsg = $('<div />').text(message).html();
                // Add the message to the page.    
                $('#box1').append('<li><strong>' + encodedName
                    + '</strong>:&nbsp;&nbsp;' + encodedMsg + '</li>');
            };
            // Get the user name and store it to prepend to messages.
            $('#displayname').val(prompt('Enter your name:', ''));
            // Set initial focus to message input box.
            $('#message').focus();
            // Start the connection.
            $.connection.hub.start().done(function () {
                $('#sendmessage').click(function () {
                    // Call the Send method on the hub.
                    chat.server.send($('#displayname').val(), $('#message').val());
                    // Clear text box and reset focus for next comment.
                    $('#message').val('').focus();
                });
            });
        });
    </script>
</body>
</html>

上图:

$('#box1').append('<li><strong>' + encodedName
                    + '</strong>:&nbsp;&nbsp;' + encodedMsg + '</li>');

有些数据被添加到我的div中,它是一个带边框的矩形,每当我写入文本框时,会显示一个新数据,矩形会变大,但我想显示新的div(矩形)每次我写一个新文本时都超过一个。怎么做?

1 个答案:

答案 0 :(得分:0)

我认为你的代码是正确的但是你必须检查书面文本是否先前是否依赖div。如果它已经存在则你必须做什么,但如果它不存在则将你的文本附加到div。