我正在尝试使用jQuery动态设置多个子元素的宽度。我想要做的是以下
我有这个:
$(document).ready(function() {
var setStepsWidth = function(stepsContainer) {
var el = stepsContainer,
count = stepsContainer.length,
childrenCount = 0;
for( var i = 0; i < count; i++ ) {
childrenCount = el[i].children.length;
var containerChildren = el[i].children;
console.log(containerChildren);
for(var j = 0; j < childrenCount; j++) {
//test to see if it's working
childrenCount[j].css('background-color', 'red');
}
}
};
setStepsWidth($('.steps-container'));
});
代码返回错误:&#34;未捕获的TypeError:无法读取属性&#39; css&#39;未定义&#34;
我错过了什么?
答案 0 :(得分:2)
儿童财产不正确。通过函数“children()”检索子项。见下文:
$(document).ready(function() {
var setStepsWidth = function(stepsContainer) {
var el = stepsContainer,
count = stepsContainer.length,
childrenCount = 0;
for( var i = 0; i < count; i++ ) {
childrenCount = el[i].children().length;
var containerChildren = el[i].children();
console.log(containerChildren);
for(var j = 0; j < childrenCount; j++) {
//test to see if it's working
childrenCount[j].css('background-color', 'red');
}
}
};
setStepsWidth($('.steps-container'));
});
或者,您可能需要考虑像这样编写它而不是使用数组元素。不确定这是性能上升还是下降,但这就是我写它的方式:
jQuery(document).ready(function() {
function _stepsWidth(__stepsContainer) {
jQuery.each(__stepsContainer.children(), function() {
jQuery(this).css('background-color', 'red');
});
}
_stepsWidth(jQuery('.steps-container'));
});
如果你想要递归(不确定那是你所追求的),这就是你想要的:
jQuery(document).ready(function() {
function _stepsWidth(__stepsContainer) {
jQuery.each(__stepsContainer.children(), function() {
jQuery(this).css('background-color', 'red');
_stepsWidth(jQuery(this));
});
}
_stepsWidth(jQuery('.steps-container'));
});
我也刚刚意识到你没有使用单个容器,所以如果你的宽度命令特定于每个容器,你需要这样做:
jQuery(document).ready(function() {
function _stepsWidth(__stepsContainer) {
jQuery.each(__stepsContainer.children(), function() {
jQuery(this).css('background-color', 'red');
});
}
jQuery.each(jQuery('.steps-container'), function() {
_stepsWidth(jQuery(this));
});
});
试试吧。 :)
答案 1 :(得分:2)
你正在做一些非常简单的恶劣天气。
.each()
$(document).ready(function() {
function setStepsWidth($containers) {
$containers.each(function(i, el) {//iterate through the containers
var $children = $(el).children();//find steps in current iteration's container.
$children.width(100 / $children.length);//calculate width and apply it to all steps in current iteration's container.
});
}
setStepsWidth($('.steps-container'));
});
或者,如果步骤是动态的,您可以选择附加“setStepsWidth”事件处理程序,只要添加或删除步骤就可以触发该处理程序。
例如:
$(document).ready(function() {
$(document).on('setStepsWidth', '.steps-container', function() {
var $children = $(this).children();
$children.width(100 / $children.length);
});
});
<强> DEMO 强>