使用jquery在ul中添加li元素 [英] add li element in ul using jquery

查看:1391
本文介绍了使用jquery在ul中添加li元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试制作简单的待办事项列表。这是我的HTML代码:

I try make simple todo list. This is my html code:

<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>

然后我尝试使用jquery从i输入字段读取并应用于现有的ul元素。但是当我在chrome中尝试它时,我添加的新元素会让我显示半秒并删除。
这是我的js代码:

Then I try use jquery to read from i input field and apppend to existing ul element. But when i try it in chrome my new added element show me for half of second and remove. Here is my js code:

  $(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>');
    });
});

这篇关于使用jquery在ul中添加li元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆