如何在jquery中添加新的<li>

时间:2017-10-01 10:48:15

标签: jquery

我在jquery上完成了'追加'的教训,并希望制作简单的列表 显示输入值并创建新的其他列表以在提交后执行相同操作,但它会覆盖前一个, 这就是我能做的一切,你能告诉我我错过了什么吗? 谢谢,我很抱歉我是初学者

$(function() {
  $('#submit').on('click', function() {
    var myTitle = $('#title').val();
    var myParagraph = $('#par').val();
    $('.list li').html('<h1>' + myTitle + '</h1></br><p>' + myParagraph + '</p>');
    if ($('.list .item').length > 1) {
      $(".list").append('<li></li>');
    }
  });
});
ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

li {
  border-left: 3px solid orangered
}

input {
  display: block
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class='list'>
  <li class='item'>
    <h1 class='title'></h1>
    <p class='paragraph'></p>
  </li>
  <ul>
    <label>title</label>
    <input id='title' type='text' required>
    <label>Paragraph</label>
    <input id='par' type='text' required>
    <input id='submit' type='submit'>

1 个答案:

答案 0 :(得分:2)

    namespace ConsoleApp2
    {
        class Numbers
        {
            public static void Cost(float cost, int height, int weight)
            {
                //Calculating the price of it
                float result = cost * weight * height;
                Console.WriteLine(result + "is the price");
            }
        }
        class Program
        {

            static void Main(string[] args)
            {
                int height, weight;
                height = 5;
                weight = 10;
                float cost = 0.5f;
                Numbers Numbers = new Numbers();
                Numbers.Cost(cost, height, weight );
                Console.ReadLine();
            }
        }
    }

为什么我使用计数器变量?

因为你最初有一个li,所以即使没有追加数据,长度也会返回1。附加数据后,lenth仍然只有1。

&#13;
&#13;
$('.list li').html(something);  //will overwrite
$('.list li').append(something); //will append to end
$('.list li').prepend(something); //will append to beginning
&#13;
$(function() {
    var counter = 0;
    $('#submit').on('click', function() {
        counter++;
        var myTitle = $('#title').val();
        var myParagraph = $('#par').val();

        if (counter > 1) {
            $('.list').prepend('<li><h1>' + myTitle + '</h1></br><p>' + myParagraph + '</p></li>');
        } else {
            $('.list li').html('<h1>' + myTitle + '</h1></br><p>' + myParagraph + '</p>');
        }

    });
});
&#13;
ul {
   list-style: none;
   margin: 0;
   padding: 0;
}
li{
   border-left: 3px solid orangered
}
input{
   display: block
}
&#13;
&#13;
&#13;