我试图创建一个程序,当用户从他的朋友列表中点击一个名字时,会弹出一个聊天框,我希望我的聊天框与他点击的用户一样多。不过我的问题是,我只能制作一个聊天框,我怎样才能创建一个多个聊天框并拥有一个唯一的ID?
这是我的html和php:
聊天列表:
<id = "chat_lists">
//my friend names goes here.
//you can ignore this codes, but i'll put this for
those people who want to see what's happening.
//selects all the friends of this user
if($run_query = mysqli_query($con,$query_select))
{
while($row = mysqli_fetch_assoc($run_query))
{
$chat_name = $row['full_name'];
$seen = $row['seen'];
$user_id = $row['users_id'];
if($seen == 'online')
{
$color = "green";
}
else
{
$color = "gray";
}
if($user_id !=$get_user)
{
echo "<div id = $user_id class = 'chat_div'><a class = 'chat_name'>".$chat_name."</a>"."<a class = 'seen' style = 'color:$color'>".$seen."</a></div>".'<br/>';
}
}
}
</div>
聊天框:
<div id = "chat_box">
<div id = "header"><a id = "close"><i class="fa fa-close"></i></a></div>
<div id = "message_area">
<ul id = "updated_text">
</ul>
</div>
<div id = "bottom">
<textarea id="textArea" name = "message" placeholder="Send a message.."></textarea>
<input type = "submit" value = "SEND" id = "send_button">
</div>
</div>
jquery和ajax:
$('.chat_div').click(function(){
var id = $(this).attr('id'); // gets the id of the selected user
$('#chat_box').show(); // shows the chat box
$('#updated_text').text(''); //clears the data
$.ajax({
url: 'plugins/get_chatmate_id.php',
data: {id:id},
success: function(data)
{
var d = $('#message_area');
d.scrollTop(d.prop("scrollHeight")); // scrolls down the div
}
});
});
答案 0 :(得分:1)
你走了:jsfiddle
当然,这只是一个简单的解决方案,但我希望,它会对你有所帮助。
每次打开新聊天框时,都会删除openedCheckboxes
隐藏值的值。您也可以使用全局变量。然后您可以定位聊天框。添加position: absolute
并根据打开的复选框,您可以计算它们的位置。
HTML
<ul>
<li><a href="#" class="chat_friend" data-id="1">Friend 1</a></li>
<li><a href="#" class="chat_friend" data-id="2">Friend 2</a></li>
<li><a href="#" class="chat_friend" data-id="287">Friend 287</a></li>
</ul>
<input type="hidden" name="openedChatBoxes" value="0" />
<div class="chatBoxHolder"></div>
CSS:
<style>
div.chatBox {width: 150px; height: 300px; border: 1px solid #f00;}
</style>
和jQuery:
<script type="text/javascript">
$(function() {
$('.chat_friend').click(function(e) {
e.preventDefault();
var userId = $(this).data('id');
var divToShow = '<div class="chatBox" data-id="chat_box_' + userId + '" id="chat_box_' + userId + '"><div>Your chat box code here with user '+ userId + '</div><div><a href="#" class="close">close</a></div></div>';
$('.chatBoxHolder').append(divToShow);
/*
* Here you can do what you want with ajax
$.ajax({
url: 'plugins/get_chatmate_id.php',
data: {id: userId},
success: function(data) {
//$('#chat_box_' + userId); //At here, you can access your chat_box like this, but remember, this is a live element, so use 'on' function to manilulate
var d = $('#message_area');
d.scrollTop(d.prop("scrollHeight")); // scrolls down the div
}
});
*/
});
$('.chatBoxHolder').on('click', '.close', function() {
$(this).closest('.chatBox').remove();
});
})
</script>