简体   繁体   English

在创建带有onclick事件的div标签时使用object.innerHTML或$ object.append时,它也不允许我传递变量

[英]While using object.innerHTML or $object.append when creating a div tag with an onclick event it won't allow me to pass variables too it

I'm creating a chat application where when a message is received the user can click on the message and see information about it, the application works and there are no errors in any other part of the code however, when I add the message to the chat div element (in it's own div), although the message shows with the variables passed in correctly (usernames, color of text and message) when I add the onclick element it won't display the information. 我正在创建一个聊天应用程序,在该应用程序中,当收到消息时,用户可以单击消息并查看有关该消息的信息,该应用程序可以正常工作,但是在代码的任何其他部分都没有错误,但是,当我将消息添加到chat div元素(在它自己的div中),尽管当我添加onclick元素时消息显示正确传递的变量(用户名,文本和消息的颜色),但它不会显示信息。

I have tried two possible methods: 我尝试了两种可能的方法:

Using jquery and appending: 使用jQuery并附加:

    $chat.append("<div id =\'"+user+"\' style=\'color:"+color+";\' onclick='alert("+user+")'>"+user+ ": " + msg + "<br/></div>");

Using innerHTML: 使用innerHTML:

    var content = chat.innerHTML;
    chat.innerHTML = content + "<div id=\'"+user+"\' style=\'color:"+color+";\' onclick='alert("+user+")'>"+user+ ": "+msg+"<br/><div>";        

As said, everything else works fine but the onclick function does not work and displays an alert box but with no information just "[object HTMLcollection]". 如前所述,其他所有东西都可以正常工作,但是onclick函数不起作用,并显示警报框,但仅包含“ [object HTMLcollection]”信息。

You have something strange with quotes. 你引号有些奇怪。 Try this: 尝试这个:

$('.chat').append('<div id =' + user + ' style=color:' + color + ';onclick=alert("' + user + '")>' + user + ': ' + msg + '<br/></div>');

EDIT: You don't need to add extra quotes for id value or style value but need to add it for alert argument instead. 编辑:您不需要为id值或样式值添加额外的引号,而是需要为警报参数添加它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM