JQuery附加不正常工作

时间:2013-07-30 13:01:50

标签: 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

由于

1 个答案:

答案 0 :(得分:2)

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

$("#studentsQuestion").empty().html(question);
相关问题