javascript - JQuery 追加无法正常工作

标签 javascript jquery websocket socket.io

我正在使用带有 JQuery 的套接字,在套接字的消息调用中,我想在我的 html 页面中附加一个 div,但是一旦加载页面,我就会看到已经附加了一个额外的 div,如何防止它附加页面加载时。

其次,当附加一个 div 时,div 内有一个带有 id=answerit 的按钮,我在其中添加了 onclick 功能。但是当附加 div 并尝试单击答案按钮时,它不会调用 onclick 函数,但是当页面重新加载时它就会起作用

我的代码是

  Student.socket.onmessage = function (message) {
            //alert(message.data);
            $( document ).ready(function() {
            var str = message.data;
            var ques = str.split(":");
            var questionId = ques[0];
            var questionText = ques[1];
            var question = 
                "<div class='span11' style='border:2px solid; border-radius:5px; background-color:#b0c4de;'>"+
                    "<div style='width:30px; float:left;'>" +
                        "<div class='voteup'><a id="+questionId+" vote='true' title='This answer is useful' style='cursor:pointer'>up</a></div>"+
                        "<div class='votedown'><a id="+questionId+" vote='false' title='This answer is not useful' style='cursor:pointer'>down</a></div>"+
                    "</div>"+
                    "<div style='float:left;'>"+
                        "<div style='margin-top:5px' class='span10'>"+
                            "<span>"+questionText+"</span>"+
                            "<button id="+questionId+" style='float:right' class='answerit btn'>Answer It</button>"+
                            "<button id="+questionId+" style='float:right' class='showAnswers btn'>Show Answers</button>"+
                        "</div>"+
                    "</div>"+
                "</div>";
            $('#studentsQuestions').append(question);  
            });
        };

HTML 是

<div id="studentsQuestions"></div>

每次加载页面时,我都会看到一个额外的 div 已经存在,其中包含未定义的文本

谢谢

最佳答案

如果您愿意,可以在附加新内容之前清理 div#studentsQuestions

$("#studentsQuestion").empty().html(question);

关于javascript - JQuery 追加无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17947767/

相关文章:

javascript - Aurelia - 纯 HTML 自定义元素的内联定义

jquery - 如何在表格行上使用 slideDown(或显示)功能?

javascript - 使用 window.location.href 防止 'Confirm Navigation' 警报

python - 高速公路 Websocket : listen to local port and transfer messages to clients connected to a public port

javascript - 如何获得(显示:none)element height using pure JavaScript?

javascript - 显示元素和类名

javascript - Puppeteer 查找阴影元素列表并获取 ElementHandles 列表

javascript - Jquery 文本框的简单实时所见即所得编辑器

websocket - 如何通过 websockets 连接到 RSK 公共(public)节点?

javascript - 通过 PHP session 进行服务器身份验证