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

Jquery: $.each() returns value then ends

本文关键字:返回值 然后 结束 each Jquery      更新时间:2023-09-26

我有jQuery代码来调整几个iframe基于他们在容器。当我在没有.each()操作符的情况下这样做时,所有的iframe都使用相同的div来确定它们的大小。对于.each(),操作员运行时发出警报,但不继续执行功能。

Codepen: 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迭代展开的元素,所以你试图调用data()在一个本地DOM节点

$.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
        });
    }
});