Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
452 views
in Technique[技术] by (71.8m points)

for each JavaScript Support in IE?

I have this code:

<script>
function toggle(source) {

  checkboxes = document.getElementsByName('DG1');
  for each(var checkbox in checkboxes)
    checkbox.checked = source.checked;

  checkboxes = document.getElementsByName('DG2');
  for each(var checkbox in checkboxes)
    checkbox.checked = source.checked;

  checkboxes = document.getElementsByName('DG3');
  for each(var checkbox in checkboxes)
    checkbox.checked = source.checked;

  checkboxes = document.getElementsByName('DG4');
  for each(var checkbox in checkboxes)
    checkbox.checked = source.checked;

  checkboxes = document.getElementsByName('DG5');
  for each(var checkbox in checkboxes)
    checkbox.checked = source.checked;
}
</script>

<input type="checkbox" onClick="toggle(this)" />Select All<br/>

<form method=POST action="DGUsageServlet">
    <input type="checkbox" name="DG1">DG1</input>
    <input type="checkbox" name="DG2">DG2</input>
    <input type="checkbox" name="DG3">DG3</input>
    <input type="checkbox" name="DG4">DG4</input>
    <input type="checkbox" name="DG5">DG5</input>
</form>

How can I make the above script to work in IE?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Note that Firefox no longer supports for each loops, so this applies to every browser, not just Internet Explorer. See this MDN article for alternatives.


Internet Explorer doesn't support "for each" loops (along with other modern browsers, which have dropped support for them). You will need to change the code to use regular for loops:

function toggle(source) {
    var checkboxes = document.getElementsByName('DG1');
    for (var i = 0; i < checkboxes.length; i++) {
        checkboxes[i].checked = source.checked;
    }
    ...
}

Or, you could use a library like jQuery and do it like this:

function toggle(source) {
    $("input[name^=DG]").attr("checked", source.checked);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...