[英]Javascript - how to add new div dynamically and append data to it
我基本上是在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>: ' + 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>: ' + encodedMsg + '</li>');
一些數據添加到我的div中,它是一個帶邊框的矩形,每當我將某物寫入文本框時,都會顯示一個新數據,並且矩形會越來越大,但是我想在每個上方顯示新的div(rectangle)我寫新文字的時間。 怎么做?
我認為您的代碼是正確的,但是您必須檢查是否在div之前附加了書面文本。如果已經添加了,則您什么都不要做,但是如果不存在,則將文本附加到div。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.