我有 jQuery 代码可以根据它们所在的容器调整多个 iframe 的大小。当我在没有 .each()
运算符的情况下执行此操作时所有 iframe 使用相同的 div 来确定它们的大小的。使用 .each()
时,运算符(operator)会按照警报的方式运行,但不会继续执行该功能。
代码笔: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
});
}
});
关于javascript - Jquery: $.each() 返回值然后结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38855958/