简体   繁体   English

如何从 JavaScript 中动态创建的元素中获取文本

[英]How do I Get Text from Dynamically created element in JavaScript

I am dynamically creating Div Text in JS and was wondering how I access the various text upon click.我在 JS 中动态创建 Div 文本,并且想知道如何在单击时访问各种文本。

Here is what I have tried so far;到目前为止,这是我尝试过的;

My Dynamically created div我的动态创建的 div

function Message(Side, message) {

var divChat = '<div class="direct-chat-msg ' + Side + '">' +
                  '<div id="myDiv" class="direct-chat-text">' + message + '</div>' +

                    '<div id="accountMenu">' +
                    '<li onclick = "getMessage(' + message + ')" id="replyDiv">Reply</li>' +
                    '<li>Preferences</li>' +
                    '</ul>' +
                    '</div></div>';

    $('#divChatWindow').append(divChat);

}

JS when the li is clicked on.单击li时的 JS。

 function getMessage(str) {
     alert(str);
 }

The error I am getting is:我得到的错误是:

Uncaught ReferenceError: *whaeverthemessageis* is not defined
    at HTMLLIElement.onclick

What is the best solution to solve this problem?解决此问题的最佳解决方案是什么?

Thanks =)谢谢 =)

You have malformed html using single and double quotes.您使用单引号和双引号将 html 格式错误。 The message is being treated as a variable, not a string, hence the undefined error.该消息被视为变量,而不是字符串,因此出现未定义的错误。

replace:代替:

'<li onclick = "getMessage(' + message + ')" id="replyDiv">Reply</li>' +

with this:有了这个:

'<li onclick = "getMessage(\'' + message + '\')" id="replyDiv">Reply</li>' +

I'm not exactly sure what the problem is, but here is a working Playcode我不确定问题出在哪里,但这是一个有效的Playcode

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

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