简体   繁体   English

附加<li class>到<ul class>使用 jQuery

[英]Append <li class> to <ul class> with jQuery

When I run the function in the browser, "[object Object]" shows up instead of the text stored inside the variable $new_comment.当我在浏览器中运行该函数时,会显示“[object Object]”而不是存储在变量 $new_comment 中的文本。 I wish to append user inputs.我希望附加用户输入。

HTML : HTML :

<li class="list-group-item">"User comments"</li>

<div class="comments">
    <ul class="list-group"></ul>
</div>

Js : JS:

var addCommentFromInputBox = function() {
    var $new_comment;

    if ($(".input-group input").val() !== "") {
        $new_comment = $("<p>").text($(".input-group input").val());
        $new_comment.hide();

        $(".list-group").append('<li class="list-group-item">' + ($new_comment) + '</li>');
        $new_comment.fadeIn();
        $(".input-group input").val("");
    }
};

Everything runs fine when I change the code to:当我将代码更改为:

$(".list-group").append($new_comment);

But I wish to style it with Bootstrap.但我想用 Bootstrap 来设计它。

You can use it something like this $(".list-group").append($('<li class="list-group-item"></li>').html($new_comment));你可以像这样使用它$(".list-group").append($('<li class="list-group-item"></li>').html($new_comment));

Here this the full demo code这是完整的演示代码

 addCommentFromInputBox = function() { var $new_comment; if ($(".input-group input").val() !== "") { $new_comment = $("<p>").text($(".input-group input").val()); $new_comment.hide(); $(".list-group").append($('<li class="list-group-item"></li>').html($new_comment)); $new_comment.fadeIn(); $(".input-group input").val(""); } } addCommentFromInputBox();
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="comments"> <ul class="list-group"> </ul> </div>

var listGroupItem = $('<li class="list-group-item"></li>').html($new_comment)
$(".list-group").append($listGroupItem);

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

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