简体   繁体   English

使用jquery在ul中添加li元素

[英]add li element in ul using jquery

I try make simple todo list. 我尝试制作简单的待办事项列表。 This is my html code: 这是我的HTML代码:

<form>
   Task: <input type="text" name="task" id="input">
   <button>Submit</button>
</form>

<br>

<h2>What you need to do</h2>
<ul id="list">

</ul>

Then I try use jquery to read from i input field and apppend to existing ul element. 然后我尝试使用jquery从i输入字段读取并应用于现有的ul元素。 But when i try it in chrome my new added element show me for half of second and remove. 但是当我在chrome中尝试它时,我添加的新元素会让我显示半秒并删除。 Here is my js code: 这是我的js代码:

  $(document).ready(function() {
    $('button').click(function() {
            var new_task = $('#input').val();
            $('#list').append('<li>'+new_task+'</li>');
    });
  });

A button inside a form has a default type of submit, and will submit the form, you need to prevent that or set a different type on the button : 表单中的按钮具有默认的提交类型,并且将提交表单,您需要阻止该表单或在按钮上设置不同的类型:

$(document).ready(function() {
    $('button').on('click', function(e) {
        e.preventDefault();
        var new_task = $('#input').val();
        $('#list').append('<li>'+new_task+'</li>');
    });
});

Try this 尝试这个

HTML HTML

<form>
  Task: <input type="text" name="task" id="input">
  <button>Submit</button>
  <br>

 <h2>What you need to do</h2>
 <ul id="list">

 </ul>
</form>

JS JS

$(document).ready(function() {
 $('button').click(function() {

  var new_task = $('#input').val();
  $('#list').append('<li>'+new_task+'</li>');
  return false;
 });
});

Demo 演示

You must return false; 你必须return false; at the end of your function: 在你的功能结束时:

$('button').click(function() {
  var new_task = $('#input').val();
  $('#list').append('<li>'+new_task+'</li>');
  return false;   // This is new line of code
});

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

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