使用jquery将项添加到列表中

时间:2013-06-18 15:23:28

标签: javascript jquery html

我有一个我无法弄清楚的快速问题。我正在使用此代码:

http://jsfiddle.net/spadez/ZTuDJ/32/

// If JS enabled, disable main input
$("#responsibilities").prop('disabled', true);
// $("#responsibilities").addClass("hidden");

// If JS enabled then add fields
$("#resp").append('<input placeholder="Add responsibility" id="resp_input" ></input><input type="button" value="Add" id="add"> ');

// Add items to input field
var eachline='';
$("#add").click(function(){
    var lines = $('#resp_input').val().split('\n');
    var lines2 = $('#responsibilities').val().split('\n');
    if(lines2.length>10)return false;
    for(var i = 0;i < lines.length;i++){
        if(lines[i]!='' && i+lines2.length<11){
        eachline += lines[i] + '\n';
        }    
    }

        $('#responsibilities').text($("<div>" + eachline + "</div>").text() );

    $('#resp_input').val('');
});  

这个想法是你在责任字段中输入内容并将其插入文本区域。我还想做的是,当一个项目插入到文本区域时,它还会以下面的列表格式将其打印出来:

<li>inserted item 1</li> <li>inserted item 2</li>

我是javascript的新手,但根据在网上找到的信息,这是我最好的尝试:

$("#resp").append('<li> +eachline </li> ')   

3 个答案:

答案 0 :(得分:1)

$('#responsibilities').text($("<div>" + eachline + "</div>").text() ).before("<li>"+lines+"</li>");

演示---> http://jsfiddle.net/ZTuDJ/34/

答案 1 :(得分:1)

http://jsfiddle.net/pjdicke/ZTuDJ/35/

您需要创建一个<ul>,然后在下面添加

$('#responsibilities').text( $("<div>" + eachline + "</div>").text() );

// add this line after above 
$('<li>' + lines + '</li>').appendTo('#list');

答案 2 :(得分:0)

我已经在你之前的问题中为你解决了这个问题。

Jquery adding items to a list without reloading page

http://jsfiddle.net/blackjim/VrGau/15/

var $responsibilityInput = $('#responsibilityInput'),
    $responsibilityList = $('#responsibilityList'),
    $inputButton = $('#addResp'),
    rCounter = 0;

var addResponsibility = function () {
    if(rCounter < 10){
        var newVal = $responsibilityList.val()+$responsibilityInput.val();
        if(newVal.trim()!==''){
            var newLi = $('<li>');
            $('ul#respList').append(newLi.text(newVal));
            $responsibilityList.val('');
            rCounter+=1;    
        }
    }
}

$inputButton.click(addResponsibility);