我有一个选择框,选择“其他”选项后,将显示第二个选择框(超过10k的巨大列表)。这在IE和Mozilla中运行正常,但在Chrome中遇到了未捕获的rangeError。如何调试和解决此问题?



<!DOCTYPE html>
<html>

<body>

  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script>
      $(document).ready(function() {

        $('#thisIsTheSelectBox').change(function() {

          var otherSelectBoxId = $(this).attr('id') + "xyz123";

          if ($(this).val() === "Others") {
            var otherSelectBox = "<select id='" + otherSelectBoxId + "' name='' unit='' uniquename='' class=' ' required='true'> " +
              "<option value='option 1'>option 1</option>" +
              "<option value='option 2'>option 2</option>" +
              ...
              "<option value='option 10000'>option 10000</option>" +
              "</select>";
            $(this).after(otherSelectBox);
          } else {
            $("#" + otherSelectBoxId).remove();
          }
        });

      });
    </script>
  </head>
  <table>
    <tr>
      <td width="330" valign="top">
        <select id="thisIsTheSelectBox" name="" required="true">
          <option value=''>-- Options --</option>
          <option value='1'>test1</option>
          <option value='2'>test2</option>
          <option value='Others'>Others</option>
        </select>
      </td>
    </tr>
  </table>
</body>

最佳答案

可能是内部错误。无需构建长字符串,而是可以在循环中添加每个元素,而使代码更轻便,更易于维护。

码:

$(document).ready(function () {

    $('#thisIsTheSelectBox').change(function () {

        var otherSelectBoxId = $(this).attr('id') + "xyz123";

        if ($(this).val() === "Others") {
            var otherSelectBox = "<select id='" + otherSelectBoxId + "' name='' unit='' uniquename='' class=' ' required='true'> ";
            for (var i = 0; i <= 10000; i++) {
                otherSelectBox += "<option value='option" + i + "'>option " + i + "</option>";
            }
            otherSelectBox += "</select>";
            $(this).after(otherSelectBox);
        } else {
            $("#" + otherSelectBoxId).remove();
        }
    });

});


演示:http://jsfiddle.net/IrvinDominin/4gk5zd5t/

09-26 19:04
查看更多