JavaScript 循环
我有一个 javascript 片段,它循环遍历所有输入(表中的所有行),如果在一行中选中一个复选框,它会检查所有行中的所有复选框。
我实际上需要它来检查同一行中的第二个复选框,而不是所有行,所以我需要编辑 javascript 片段,它会在其中递增
//loop through all inputs
for(i = 0; i < inputs.length; i++)
<script type="text/javascript">
var mainchecked = false;
function checkAll() {
//get all input elements
var inputs = document.getElementsByTagName('input');
//if the box is being checked
if(!mainchecked) {
//loop through all inputs
for(i = 0; i < inputs.length; i++) {
//does it have autocheck?
if(inputs[i].className == 'autocheck') {
//then check the box!
inputs[i].checked = "checked";
}
}
mainchecked = true;
} else {
//box is being unchecked, uncheck everything
for(i = 0; i < inputs.length; i++) {
inputs[i].checked = "";
}
mainchecked = false;
}
}
</script>
I've got a javascript snippet that loops through all inputs (all rows in a table) and if one checkbox is checked in a single row, it checks all checkboxes in all rows.
I actually need it to check a 2nd checkbox in the same row not all rows so I need to edit the javascript snippet, where it increments
//loop through all inputs
for(i = 0; i < inputs.length; i++)
<script type="text/javascript">
var mainchecked = false;
function checkAll() {
//get all input elements
var inputs = document.getElementsByTagName('input');
//if the box is being checked
if(!mainchecked) {
//loop through all inputs
for(i = 0; i < inputs.length; i++) {
//does it have autocheck?
if(inputs[i].className == 'autocheck') {
//then check the box!
inputs[i].checked = "checked";
}
}
mainchecked = true;
} else {
//box is being unchecked, uncheck everything
for(i = 0; i < inputs.length; i++) {
inputs[i].checked = "";
}
mainchecked = false;
}
}
</script>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不要循环遍历所有输入,而是循环遍历表行并处理每行中的输入。以下代码假设该行的控制复选框位于该行中找到的第一个输入中,并且该功能适用的行中的所有其他复选框都将类别设置为“autocheck”;我将让您根据您的具体情况进行修改(例如,您可能需要检查是否
type=="checkbox"
)。我还没有对此进行测试,但它应该足以让您继续下去。
更新:刚刚在您的评论中看到您似乎是从控制复选框的
onclick
触发此功能。如果是这样,那么您可以将该复选框的引用传递给您的函数,然后仅处理它所在的行,如下所示:Google“mdcparentnode”以获取更多信息。
Don't loop through all inputs, loop through the table rows and process the inputs within each row. The following code assumes the controlling checkbox for the row is in the first input found within the row and that all other checkboxes in the row that this functionality applies to will have the class set to "autocheck"; I'll leave it to you to modify this as needed for your specific case (e.g., you might need to check whether
type=="checkbox"
).I haven't tested this, but it should give you enough to go on.
UPDATE: just saw in your comments that you seem to be triggering this functionality from the
onclick
of the controlling checkboxes. If that is so then you can pass a reference to that checkbox to your function and then process only the row it is in, as follows:Google "mdc parentnode" for more info.