我有这个小提琴:http://jsfiddle.net/qc4uje71/16/
创建带有复选框的列表。我想在单击按钮时获取选中项目的名称。
我有检查项目的索引
alert(i).
如何获得已检查项目的名称(即:item0,item1 ..)?
最佳答案
您可以将nextSibling
与nodeValue
一起使用:
for (var i = 0; i < 5; i++) {
var node = document.createElement("li");
var x = document.createElement("INPUT");
x.setAttribute("type", "checkbox");
x.id = "in" + i;
node.appendChild(x);
var textnode = document.createTextNode("item" + i);
node.appendChild(textnode);
document.getElementById("myList").appendChild(node);
}
function displayCheckedGroup() {
for (var i = 0; i < 5; i++) {
if (document.getElementById("in" + i).checked == true) {
//change this
alert(document.getElementById("in" + i).nextSibling.nodeValue);
}
}
}
ul {
list-style: none;
padding: 0px;
margin: 0px;
}
li {
clear: left;
font-size: 25px;
padding: 3px 0px 3px 10px;
margin: 0px;
}
li input {
float: right;
margin-right: 15px;
width: 25px;
height: 25px;
}
li:nth-child(even) {
background-color: #eee;
}
<ul id="myList">
</ul>
<button onclick="displayCheckedGroup()">Display checked items</button>
您也可以更改一下功能:
function displayCheckedGroup() {
var elem, i;
for (i = 0; i < 5; i++) {
elem = document.getElementById("in" + i)
if (elem.checked) {
alert(elem.nextSibling.nodeValue);
}
}
}
参考文献
Node.nextSibling
Node.nodeValue
关于javascript - 获取列表中的已检查项目,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30510894/