I am trying to solve this problem where I am using chat tutorial http://www.sanwebe.com/2013/05/chat-using-websocket-php-socket . I am attempting to create anchors that that will go to each users profile if clicked on. The problem is that during testing with multiple users the links only direct to the very first user in the room. I have spent a fair amount of time trying to figure this out. How do I get separate clickable links? I am using CodeIgniter with links processed by a controller. I cannot fathom how I would perform any loop or while statements in this structure.
Javascript with HTML
websocket.onmessage = function(ev) {
var msg = JSON.parse(ev.data); //PHP sends Json data
var type = msg.type; //message type
var umsg = msg.message; //message text
var uname = msg.name; //user name
var ucolor = msg.color; //color
if(type == 'usermsg')
{
$('#message_box').append("<div><span class=\'user_name\' style=\'color:#'+ucolor+'\"><button type='button' class='greenButton' onclick='proceed()' id='mem_name' value='"+uname+"'>"+uname+"</button></span> : <span class=\"user_message\">"+umsg+" </span></div>" );
}`
JS Function
function proceed (button) {
var mem_name = $('#mem_name').val();
var form = document.createElement('form');
form.setAttribute('method', 'post');
form.setAttribute('action', 'member_chat');
form.style.display = 'hidden';
form.setAttribute("target", "formresult");
var hiddenField = document.createElement("input");
hiddenField.setAttribute('name', 'mem_chat');
hiddenField.setAttribute('value', mem_name)
form.appendChild(hiddenField);
document.body.appendChild(form)
form.submit();
}
At a high level, your issue is that all your inserted buttons have the same id, mem_name
. IDs must be unique, so $("#mem_name")
stops after finding the first mafch.
The quick fix here is to pass this
in your inline click listener:
onclick="proceed(this)"
And use $(button)
(ie, the parameter to proceed
) instead of $("#mem_name")
.
A more elegant solution would be to eliminate inline listeners at all and use jQuery's .on
delegation. Change the id=mem_name
to class=mem_name
, eliminate the onclick
listener, and add this code to run once only (ie, not inside a message event listener):
$("#message_box").on("click", ".mem_name", proceed);
Then change the $("#mem_name")
to $(this)
. This will cause proceed
to run any time an element with a mem_name
class is clicked inside of #message_box
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.