使用 jquery 在 ul 中添加 li 元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17183713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
add li element in ul using jquery
提问by SuperManEver
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. But when i try it in chrome my new added element show me for half of second and remove. Here is my js code:
然后我尝试使用 jquery 从 i 输入字段中读取并附加到现有的 ul 元素。但是当我在 chrome 中尝试它时,我新添加的元素向我展示了半秒并删除。这是我的js代码:
$(document).ready(function() {
$('button').click(function() {
var new_task = $('#input').val();
$('#list').append('<li>'+new_task+'</li>');
});
});
回答by adeneo
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>');
});
});
回答by Amit
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;
});
});
回答by Precastic
You must return false;
at the end of your function:
您必须return false;
在函数结束时:
$('button').click(function() {
var new_task = $('#input').val();
$('#list').append('<li>'+new_task+'</li>');
return false; // This is new line of code
});