jQuery巨大的selectbox导致Uncaught RangeError:超过了最大调用堆栈大小

jQuery huge selectbox result in Uncaught RangeError: Maximum call stack size exceeded

本文关键字:过了 调用 堆栈 巨大 selectbox 导致 RangeError Uncaught jQuery      更新时间:2023-10-21

我有一个选择框,选择"其他"选项后,将显示第二个选择框(超过10k的巨大列表)。这在IE和Mozilla中运行良好,但在Chrome中达到了未捕获的范围错误。如何调试和修复此问题?

<!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/