0

嗨,我正在尝试在我的网站上创建一个评论部分,我编写的代码将我输入的评论放在已经输入的评论下方。

我真正想做的是将新输入的评论放在旧评论之上(如 facebook 或 youtube 或任何其他网站 - 当您输入评论时,它会出现在旧评论上方(在第一行))我通过使用 javascript 来做到这一点?谢谢你。下面是我写的代码。

<input id = "txtboxComment" type = "text" onkeyup = "typeComment(event)" placeholder = "Write a comment"/>
<div id = "comment"></div>
#txtboxComment { 
    float: left;
    width: 600px;
    height: 25px;
    margin-left: 10px;
    margin-top: 10px;}

#comment {
    border: solid 1px;
    float: left;
    width: 602px;
    height: auto;
    margin-left: 51px;
    margin-top: 10px;
}
function typeComment(e) {
    co = document.getElementById("txtboxComment");
    if (e.keyCode == 13) {
        co.click();
        document.getElementById("comment").innerHTML += "<pre>" + co.value  + "\n" + "</pre>";
}
4

5 回答 5

1

利用

document.getElementById("comment").innerHTML = "<pre>" + co.value  + "\n" + "</pre>" + document.getElementById("comment").innerHTML;
于 2016-04-25T07:22:55.537 回答
0

我猜你希望你的最新文本应该放在另一个 div 的顶部,

JS

$("#pcontainer").prepend($('<p>This paragraph was added by jQuery.</p>').fadeIn('slow'));
于 2016-04-25T07:22:01.827 回答
0

我会得到 div 的内容(所有旧评论)并将其分配给变量 x。然后获取输入值,并将其分配给变量 y。然后将 div 的内容设置为 y+x。

于 2016-04-25T07:22:56.787 回答
0

您正在将新内容附加到#comment. 如果我正确理解了这个问题,你想把它放在前面。将此行更改document.getElementById("comment").innerHTML += "<pre>" + co.value + "\n" + "</pre>";

document.getElementById("comment").innerHTML = "<pre>" + co.value  + "\n" + "</pre>" + document.getElementById("comment").innerHTML;
于 2016-04-25T07:22:56.970 回答
0

仅使用 javascript 执行此操作,因为您的代码中没有jQuery,尽管您已标记它

function typeComment(e){  // Execute this function on enter key
    co = document.getElementById("txtboxComment");
    var _comment = document.createElement('pre'); //create a pre tag 
   if (e.keyCode == 13) {
        co.click();
        _comment.textContent = co.value; //put the value inside pre tag
        var _commentDiv = document.getElementById("comment");
        if(_commentDiv.firstChild === null){ // Will validate if any comment is there
        // If no comment is present just append the child
        document.getElementById("comment").appendChild(_comment) 
        }
        else{
        // If a comment is present insert the new 
       // comment before the present first child in comment section
        document.getElementById("comment").insertBefore( _comment,_commentDiv.firstChild );
        }
   }
}

工作示例

于 2016-04-25T07:30:44.623 回答