Jquery: $.each() returns 值然后结束

Jquery: $.each() returns value then ends

我有 jQuery 代码可以根据它们所在的容器调整多个 iframe 的大小。当我在没有 .each() 运算符的情况下执行此操作时,所有 iframe 使用相同的 div 来根据他们的大小。使用 .each() 时,操作员会按照警报的方式运行,但不会继续执行该功能。

代码笔:https://codepen.io/bjackson2016/pen/oLQopy?editors=0010

$(document).ready(function(){
function resize() {
  var elements = $('.resize');
  var eachElement = $.makeArray(elements);
  alert(eachElement);
  $.each(eachElement, function(index, value) {
    alert(index + " " + value);
    var multi = value.data('wfactor');
    alert(multi);
    var ratio = value.data('ratio');
    alert(ratio);
    var minX = value.data('minw');
    alert(minX);
    var minY = value.data('minh');
    alert(minY);
    var ruler = value.siblings('.widthTest');
    alert(ruler);
    var pWidth = ruler.width();
    alert(pWidth);
    var adjWidth = pWidth * multi;
    alert(adjWidth);
    var eHeight = (Math.round(ratio * adjWidth));
    alert(eHeight);
    var unadjHeight = Math.round(ratio * pWidth);
    alert(unadjHeight);
    var eWidth = (Math.round(adjWidth));
    alert(eWidth);
    if (eHeight < minY) {
      $(this).height(minY);
      alert('changed height');
    } else {
      value.height(eHeight);
      alert('normal height');
    }
    if (eWidth < minX) {
      value.css('width', pWidth).css('height', unadjHeight);
      alert('changed width');
    } else {
      value.width(eWidth);
      alert('kept width');
    }
  });
}

resize();

$(window).resize(function() {
  resize();
});

}); 

问题是没有value.data()

data() 是一个 jQuery 函数,用 $.each 迭代解包元素,所以你试图在原生 [=22= 上调用 data() ]节点

$.each(eachElement, function(index, value) {

    // value is not a jQuery object here, you'd have to do

    var elem = $(value); // where you wrap it again.

});

试试看

$(document).ready(function() {
    $(window).on('resize', resize).trigger('resize');

    function resize() {
        $('.resize').each(function(index, element) {
        var elem = $(element);

        var multi = elem.data('wfactor'),
            ratio = elem.data('ratio'),

            ... etc

        });
    }
});