【问题标题】:Reference error function javascript引用错误函数javascript
【发布时间】:2016-06-12 00:44:27
【问题描述】:

我有以下 javascript:

$(document).ready(function () {
        // convert bytes into friendly format
        function bytesToSize(bytes) {
            var sizes = ['Bytes', 'KB', 'MB'];
            if (bytes == 0) return 'n/a';
            var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
            return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i];
        };

        // check for selected crop region
        function checkForm() {
            if (parseInt($('#w').val())) return true;
            $('.error').html('Please select a crop region and then press Upload').show();
            return false;
        };

        // update info by cropping (onChange and onSelect events handler)
        function updateInfo(e) {
            $('#x1').val(e.x);
            $('#y1').val(e.y);
            $('#x2').val(e.x2);
            $('#y2').val(e.y2);
            $('#w').val(e.w);
            $('#h').val(e.h);
        };

        // clear info by cropping (onRelease event handler)
        function clearInfo() {
            $('.info #w').val('');
            $('.info #h').val('');
        };

        // Create variables (in this scope) to hold the Jcrop API and image size
        var jcrop_api, boundx, boundy;

        function fileSelectHandler() {

            // get selected file
            var oFile = $('#image_file')[0].files[0];

            // hide all errors
            $('.error').hide();

            // check for image type (jpg and png are allowed)
            var rFilter = /^(image\/jpeg|image\/png)$/i;
            if (!rFilter.test(oFile.type)) {
                $('.error').html('Please select a valid image file (jpg and png are allowed)').show();
                return;
            }

            // check for file size
            if (oFile.size > 250 * 1024) {
                $('.error').html('You have selected too big file, please select a one smaller image file').show();
                return;
            }

            // preview element
            var oImage = document.getElementById('preview');

            // prepare HTML5 FileReader
            var oReader = new FileReader();
            oReader.onload = function (e) {

                // e.target.result contains the DataURL which we can use as a source of the image
                oImage.src = e.target.result;
                oImage.onload = function () { // onload event handler

                    // display step 2
                    $('.step2').fadeIn(500);

                    // display some basic image info
                    var sResultFileSize = bytesToSize(oFile.size);
                    $('#filesize').val(sResultFileSize);
                    $('#filetype').val(oFile.type);
                    $('#filedim').val(oImage.naturalWidth + ' x ' + oImage.naturalHeight);

                    // destroy Jcrop if it is existed
                    if (typeof jcrop_api != 'undefined') {
                        jcrop_api.destroy();
                        jcrop_api = null;
                        $('#preview').width(oImage.naturalWidth);
                        $('#preview').height(oImage.naturalHeight);
                    }

                    setTimeout(function () {
                        // initialize Jcrop
                        $('#preview').Jcrop({
                            minSize: [32, 32], // min crop size
                            aspectRatio: 1, // keep aspect ratio 1:1
                            bgFade: true, // use fade effect
                            bgOpacity: .3, // fade opacity
                            onChange: updateInfo,
                            onSelect: updateInfo,
                            onRelease: clearInfo
                        }, function () {

                            // use the Jcrop API to get the real image size
                            var bounds = this.getBounds();
                            boundx = bounds[0];
                            boundy = bounds[1];

                            // Store the Jcrop API in the jcrop_api variable
                            jcrop_api = this;
                        });
                    }, 3000);

                };
            };

            // read selected file as DataURL
            oReader.readAsDataURL(oFile);
        }
    });

这是我的 HTML:

<div id="profileUploadModal" class="modal fade" role="dialog">
                        <div class="modal-dialog">

                            <!-- Modal content-->
                            <div class="modal-content">
                                <div class="modal-header">
                                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                                    <h4 class="modal-title">Upload profilepicture</h4>
                                </div>
                                <div class="modal-body" style="text-align: center;">
                                    <div class="bbody">

                                        <!-- upload form -->
                                        <form id="upload_form" enctype="multipart/form-data" method="post" action="upload.php" onsubmit="return checkForm()">
                                            <!-- hidden crop params -->
                                            <input type="hidden" id="x1" name="x1" />
                                            <input type="hidden" id="y1" name="y1" />
                                            <input type="hidden" id="x2" name="x2" />
                                            <input type="hidden" id="y2" name="y2" />

                                            <h2>Step1: Please select image file</h2>
                                            <div><input type="file" name="image_file" id="image_file" onchange="fileSelectHandler()" /></div>

                                            <div class="error"></div>

                                            <div class="step2">
                                                <h2>Step2: Please select a crop region</h2>
                                                <img id="preview" />

                                                <div class="info">
                                                    <label>File size</label> <input type="text" id="filesize" name="filesize" />
                                                    <label>Type</label> <input type="text" id="filetype" name="filetype" />
                                                    <label>Image dimension</label> <input type="text" id="filedim" name="filedim" />
                                                    <label>W</label> <input type="text" id="w" name="w" />
                                                    <label>H</label> <input type="text" id="h" name="h" />
                                                </div>

                                                <input type="submit" value="Upload" />
                                            </div>
                                        </form>
                                    </div>
                                 </div>
                                </div>
                                </div>
                            </div>

当我运行它时,我收到以下错误:

Uncaught ReferenceError: fileSelectHandler is not defined

我不明白为什么。如我所见,功能是否已经实现?那么为什么会出现这个引用错误呢?

【问题讨论】:

    标签: javascript jquery jcrop


    【解决方案1】:

    您不需要将这些函数中的任何一个放在 document.onReady 中。

    在 document.ready 范围内声明的任何函数也必须在其中调用。如果没有,它们会在 ready() 方法退出时失去该范围。所以它在你试图调用它的范围内不存在,因此你的错误。

    定义如下:

        function bytesToSize(bytes) {
          var sizes = ['Bytes', 'KB', 'MB'];
          if (bytes == 0) return 'n/a';
          var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
          return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i];
        };
    
         // check for selected crop region
        function checkForm() {
          if (parseInt($('#w').val())) return true;
          $('.error').html('Please select a crop region and then press Upload').show();
          return false;
        };
    
         // update info by cropping (onChange and onSelect events handler)
        function updateInfo(e) {
          $('#x1').val(e.x);
          $('#y1').val(e.y);
          $('#x2').val(e.x2);
          $('#y2').val(e.y2);
          $('#w').val(e.w);
          $('#h').val(e.h);
        };
    
         // clear info by cropping (onRelease event handler)
        function clearInfo() {
          $('.info #w').val('');
          $('.info #h').val('');
        };
    
         // Create variables (in this scope) to hold the Jcrop API and image size
        var jcrop_api, boundx, boundy;
    
        function fileSelectHandler(e) {
    
          alert("I'm here!");
    
          // get selected file
          var oFile = $('#image_file')[0].files[0];
    
          // hide all errors
          $('.error').hide();
    
          // check for image type (jpg and png are allowed)
          var rFilter = /^(image\/jpeg|image\/png)$/i;
          if (!rFilter.test(oFile.type)) {
            $('.error').html('Please select a valid image file (jpg and png are allowed)').show();
            return;
          }
    
          // check for file size
          if (oFile.size > 250 * 1024) {
            $('.error').html('You have selected too big file, please select a one smaller image file').show();
            return;
          }
    
          // preview element
          var oImage = document.getElementById('preview');
    
          // prepare HTML5 FileReader
          var oReader = new FileReader();
          oReader.onload = function(e) {
    
            // e.target.result contains the DataURL which we can use as a source of the image
            oImage.src = e.target.result;
            oImage.onload = function() { // onload event handler
    
              // display step 2
              $('.step2').fadeIn(500);
    
              // display some basic image info
              var sResultFileSize = bytesToSize(oFile.size);
              $('#filesize').val(sResultFileSize);
              $('#filetype').val(oFile.type);
              $('#filedim').val(oImage.naturalWidth + ' x ' + oImage.naturalHeight);
    
              // destroy Jcrop if it is existed
              if (typeof jcrop_api != 'undefined') {
                jcrop_api.destroy();
                jcrop_api = null;
                $('#preview').width(oImage.naturalWidth);
                $('#preview').height(oImage.naturalHeight);
              }
    
              setTimeout(function() {
                // initialize Jcrop
                $('#preview').Jcrop({
                  minSize: [32, 32], // min crop size
                  aspectRatio: 1, // keep aspect ratio 1:1
                  bgFade: true, // use fade effect
                  bgOpacity: .3, // fade opacity
                  onChange: updateInfo,
                  onSelect: updateInfo,
                  onRelease: clearInfo
                }, function() {
    
                  // use the Jcrop API to get the real image size
                  var bounds = this.getBounds();
                  boundx = bounds[0];
                  boundy = bounds[1];
    
                  // Store the Jcrop API in the jcrop_api variable
                  jcrop_api = this;
                });
              }, 3000);
    
            };
          };
    
          // read selected file as DataURL
          oReader.readAsDataURL(oFile);
        }
    
        $(document).ready(function() {
          // convert bytes into friendly format
    
    
    
        });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <div id="profileUploadModal" class="modal fade" role="dialog">
      <div class="modal-dialog">
    
        <!-- Modal content-->
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">&times;</button>
            <h4 class="modal-title">Upload profilepicture</h4>
          </div>
          <div class="modal-body" style="text-align: center;">
            <div class="bbody">
    
              <!-- upload form -->
              <form id="upload_form" enctype="multipart/form-data" method="post" action="upload.php" onsubmit="return checkForm()">
                <!-- hidden crop params -->
                <input type="hidden" id="x1" name="x1" />
                <input type="hidden" id="y1" name="y1" />
                <input type="hidden" id="x2" name="x2" />
                <input type="hidden" id="y2" name="y2" />
    
                <h2>Step1: Please select image file</h2>
                <div>
                  <input type="file" name="image_file" id="image_file" onchange="fileSelectHandler()" />
                </div>
    
                <div class="error"></div>
    
                <div class="step2">
                  <h2>Step2: Please select a crop region</h2>
                  <img id="preview" />
    
                  <div class="info">
                    <label>File size</label>
                    <input type="text" id="filesize" name="filesize" />
                    <label>Type</label>
                    <input type="text" id="filetype" name="filetype" />
                    <label>Image dimension</label>
                    <input type="text" id="filedim" name="filedim" />
                    <label>W</label>
                    <input type="text" id="w" name="w" />
                    <label>H</label>
                    <input type="text" id="h" name="h" />
                  </div>
    
                  <input type="submit" value="Upload" />
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>

    【讨论】:

    • 或者,如果您不想要一堆全局函数,请在文档就绪处理程序中定义 onchange 处理程序,而不是使用内联 onchange 属性。
    【解决方案2】:

    那是因为你的函数 fileSelectHandler() 是在另一个函数中定义的。尝试将其移出 "$(document).ready(function () {..." 块

    【讨论】:

      猜你喜欢
      • 2015-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-16
      相关资源
      最近更新 更多