如何使用 Jquery 从输入动态创建带有附加文本的 ul li

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14844498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:59:38  来源:igfitidea点击:

How to dynamically create a ul li with appended text from input with Jquery

jquerydynamichtml-listsappend

提问by user2066695

I have a form that has a text input with an add button. When you click the add button it gets the text from the input and places it below in another div. I need it to be in a dynamically created unordered list that also places the text from the input inside. I need the output to look like

我有一个带有添加按钮的文本输入表单。当您单击添加按钮时,它会从输入中获取文本并将其放置在另一个 div 的下方。我需要它在动态创建的无序列表中,该列表还将输入中的文本放入其中。我需要输出看起来像

<ul> <li>text from input</li> <li>text from input again</li> </ul>

<ul> <li>text from input</li> <li>text from input again</li> </ul>

Im not sure how to properly place the append to create the list and append the text inside. I can get the text value easily and output it just not into a list. Any help about appending would be great.

我不确定如何正确放置附加内容以创建列表并将文本附加到其中。我可以轻松获取文本值并将其输出到列表中。关于附加的任何帮助都会很棒。

回答by AlexC

HTML:

HTML:

<input type="test" id="inputName" />
<button id="btnName">Click me!</button>

<ul class="justList"></ul>

JS:

JS:

$('#btnName').click(function(){
    var text = $('#inputName').val();
    if(text.length){
        $('<li />', {html: text}).appendTo('ul.justList')
    }
});

Here is the demo :

这是演示:

http://jsfiddle.net/J5nCS/

http://jsfiddle.net/J5nCS/

UPDATE:

更新:

for your comments :

供您评论:

here is the url :

这是网址:

http://jsfiddle.net/J5nCS/1/

http://jsfiddle.net/J5nCS/1/

$('#btnName').click(function(){
    var text = $('#inputName').val() + '<button>x</button>';
    if(text.length){
        $('<li />', {html: text}).appendTo('ul.justList')
    }
});

$('ul').on('click','button' , function(el){
    $(this).parent().remove()
});

回答by Losbear

something like this?

像这样的东西?

$("#yourbutton").click(function() {
    //uncomment this if you want to wipe the list before adding the LI node:
    //$("#yourUL").empty();

    $("#yourUL").append("<li>" + $("#yourinputtextbox").val() + "</li>");
});

回答by deadlock

You are looking for jQuery appendTo()

您正在寻找 jQuery appendTo()

$("button").click(function(){
    $("<li>"+$("input").val()+"</li>").appendTo("ul");
});

demo: http://jsfiddle.net/u74Ag/

演示:http: //jsfiddle.net/u74Ag/



This might be useful

这可能有用