作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有这个 fiddle :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);
}
}
}
引用资料
关于javascript - 获取列表中的勾选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30510894/
我是一名优秀的程序员,十分优秀!