如何在jQuery中动态添加List项

时间:2014-01-17 18:01:32

标签: javascript jquery

我正在开发一个移动应用,我想在用户填写表单并点击提交按钮后填充ListView。

我知道如何在jQuery中提供List View但是如何在运行时动态填充其中的项目?

2 个答案:

答案 0 :(得分:3)

你在找这样的东西吗?

jsFiddle Demo:

<强> HTML:

<div id="listView"></div>
<input type="button" id="mybutt" value="Submit" />

<强>的javascript / jQuery的:

$('#mybutt').click(function() {
    var out = '<ul><li>Item One</li><li>Item Two</li><li>Item Three</li></ul>';
    $('#listView').html(out);
});

回复您的评论:“点击按钮表单时我需要的是提交,用户在表单上输入的名字将被添加到列表中”

首先,您需要在提交表单后保留在页面上。为此,您应在提交例程中添加e.preventDefault();

$( "#target" ).submit(function( event ) {
    //Manually collect form values and 
    //Use ajax to submit form values here (see notes at bottom)
    event.preventDefault();
});

接下来,您希望获取所需字段中的数据,并将其添加到<ul>。因此,改变上面这样:

$( "#target" ).submit(function( event ) {
    var fn = $('#fname').val();
    $('ul').append('<li>' +fn+ '</li>');

    //Manually collect form values and 
    //Use ajax to submit form values here (see notes at bottom)
    event.preventDefault();
});

对于AJAX位,see this post提示。

请注意,您可以使用$('#formID').serialize();快速序列化所有表单数据。

答案 1 :(得分:0)

js小提琴:

<强> http://jsfiddle.net/7PzcN/1/

<强> HTML:

<div id="listView"></div>
<input type="text" name="firstname"/>
<input type="text" name="lastname"/>
<input type="button" id="mybutt" value="Submit" />

<强> jquery的:

$('#mybutt').click(function() {
    var out = '<ul>';
    $("input[type=text]").each(function() {
        out += "<li>" + $(this).val() + "</li>";
    });
    out += "</ul>";
    $('#listView').html(out);
});