如何在JavaScript的列表中插入复选框? [英] How to insert a checkbox in a list in javascript?
问题描述
我正在尝试使用JS创建待办事项列表.想法是在输入中编写一些内容,当用户单击按钮时,他将获得一个带有文本的复选框.
I'm trying to create a todo list with JS. The idea is to write something in the input and when the user clicks the button, he obtains a checkbox with the text on it.
问题是我不知道如何使用JS.我试图将'li'更改为输入,然后将setAttribute("type","checkbox")更改为输入,但没有任何反应.
The problem is that I don't know how can I do it with JS. I tried to change the 'li' to an input and then setAttribute("type", "checkbox"), but nothing happened.
<!DOCTYPE html>
<html>
<head>
<title>Lista de tareas personal.</title>
<meta charset='utf-8'>
<style type="text/css">
body{
font-family: Helvetica, Arial;
}
li{
width: 50%;
list-style-type: none;
font-size: 20px;
}
</style>
</head>
<body>
<h1>Lista de tareas personal.</h1>
<hr>
<br>
<button type="button" id="btn" onclick="añadirItems">Añadir Item</button>
<input type="text" id="texto">
<!---<ul id="lista"> </ul>-->
<ul id="ul"> </ul>
<script type="text/javascript">
function addItem(){
var ul = document.getElementById('ul'); //ul
var li = document.createElement('li');//li
var text = document.getElementById('texto');
li.appendChild(document.createTextNode(text.value));
ul.appendChild(li);
}
var button = document.getElementById('btn');
button.onclick = addItem
</script>
</body>
</html>
有什么建议吗?
推荐答案
您似乎没有使用jquery,因此jquery标记不会为您提供有用的答案. 您可以按照创建li元素的相同方式创建一个复选框.
You don't seem to use jquery, so the jquery tag wont get you helpful answers. You can create a checkbox in the same way you created your li element.
function addItem(){
var ul = document.getElementById('ul'); //ul
var li = document.createElement('li');//li
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.value = 1;
checkbox.name = "todo[]";
li.appendChild(checkbox);
var text = document.getElementById('texto');
li.appendChild(document.createTextNode(text.value));
ul.appendChild(li);
}
var button = document.getElementById('btn');
button.onclick = addItem;
http://jsfiddle.net/u7f5rwjs/1/
这篇关于如何在JavaScript的列表中插入复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!