HTML
<input type="checkbox" value="One" checked="checked" id="r1" name="g" />
<label for="r1">
One
</label>
<input type="checkbox" value="Two" id="r2" name="g" />
<label for="r2">
Two
</label>
<input type="button" value="Status" onclick="MyFunction()" />
Javascript
function MyFunction() {
var chk = document.getElementsByName("g");
for (var i = 0; i < chk.length; i++) {
if (chk[i].checked == true) {
alert("Checkbox at index " + i + " is checked!");
alert("Text at index " + i + chk[i].nextSibling.innerHTML);
}
}
}
在这里,我获取了已选中复选框的索引。 如何获取选中复选框的文本?
感谢您的帮助。
最佳答案
因为在许多浏览器中,nextSibling
将是一个空文本节点。
使用nextElementSibling而不是 nextSibling
The ChildNode.nextElementSibling read-only property returns the element immediately following the specified one in its parent's children list, or null if the specified element is the last one in the list.
function MyFunction() {
var chk = document.getElementsByName("g");
for (var i = 0; i < chk.length; i++) {
if (chk[i].checked === true) {
alert("Checkbox at index " + i + " is checked!");
alert("Text at index " + i + chk[i].nextElementSibling.innerHTML);
}
}
}
MyFunction();
关于javascript - HTML 复选框的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20756995/