gpt4 book ai didi

javascript - 获取列表中的勾选项

转载 作者:行者123 更新时间:2023-11-30 12:22:32 25 4
gpt4 key购买 nike

我有这个 fiddle :http://jsfiddle.net/qc4uje71/16/

创建带有复选框的列表。我想在单击按钮时获取选中项目的名称。

我有已检查项目的索引

alert(i).

如何获取选中项目的名称(即:item0、item1..)?

最佳答案

您可以将 nextSiblingnodeValue 一起使用:

  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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com