这是我的代码:

$(window).load(function() {
  var theImage = $('ul li img');
  var theWidth = theImage.width();
  //wrap into mother div
  $('ul').wrap('<div class="gallery-slide" />');
  //assign height width and overflow hidden to gallery-slide
  $('.gallery-slide').css({
    width: function() {
      return theWidth;
    },
    height: function() {
      return theImage.height();
    },
    position: 'relative',
    overflow: 'hidden'
  });
  //get total of image sizes and set as width for ul
  var totalWidth = theImage.length * theWidth;
  $('ul').css({
    width: function() {
      return totalWidth;
    }
  });
});

$('ul li img').each(function(intIndex) {
  $(this).nextAll('a').bind("click", function() {

    if ($(this).is(".next")) {
      $(this).parent('li').parent('ul').animate({
        "margin-left": (-(intIndex + 1) * theWidth)
      }, 1000);
    } else if ($(this).is(".previous")) {
      $(this).parent('li').parent('ul').animate({
        "margin-left": (-(intIndex - 1) * theWidth)
      }, 1000);
    } else if ($(this).is(".startover")) {
      $(this).parent('li').parent('ul').animate({
        "margin-left": (0)
      }, 1000);
    }
  }); //close .bind()
}); //close .each()


上面是我的代码,它抛出错误theWidth未定义。

最佳答案

如果在function-level包围的某个代码块内声明的变量仅在该代码块内可见,并且该变量在该特定代码块外不可见,则JavaScript具有ECMAScript 6 scope(在curly braces之前)。


theWidth是在$(window).load的范围内定义的,该范围超出了undefined处理程序的范围。

将所有代码包装在.load处理程序中。



$(window).load(function() {
  var theImage = $('ul li img');
  var theWidth = theImage.width();
  //wrap into mother div
  $('ul').wrap('<div class="gallery-slide" />');
  //assign height width and overflow hidden to gallery-slide
  $('.gallery-slide').css({
    width: function() {
      return theWidth;
    },
    height: function() {
      return theImage.height();
    },
    position: 'relative',
    overflow: 'hidden'
  });
  //get total of image sizes and set as width for ul
  var totalWidth = theImage.length * theWidth;
  $('ul').css({
    width: function() {
      return totalWidth;
    }
  });
  $('ul li img').each(function(intIndex) {
    $(this).nextAll('a').bind("click", function() {

      if ($(this).is(".next")) {
        $(this).parent('li').parent('ul').animate({
          "margin-left": (-(intIndex + 1) * theWidth)
        }, 1000);
      } else if ($(this).is(".previous")) {
        $(this).parent('li').parent('ul').animate({
          "margin-left": (-(intIndex - 1) * theWidth)
        }, 1000);
      } else if ($(this).is(".startover")) {
        $(this).parent('li').parent('ul').animate({
          "margin-left": (0)
        }, 1000);
      }
    });
  });
});

关于javascript - 当我编写脚本时,它显示ReferenceError:theWidth未定义,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36905388/

10-09 07:53