我有一个简单的函数,可以根据参数设置条形的宽度。
我使用 jQuery 在 .each 上调用该函数。
控制台正确记录了该语句,显示它似乎有效。但是,样式似乎被最后找到的值覆盖。
这是函数:
function barGraph(innerWidth, barWidth) {
innerWidth = parseInt(innerWidth) * .01 || .50;
barWidth = parseInt(barWidth) || 267;
// find percentage of total width
var innerWidth = Math.floor(innerWidth * barWidth);
var $innerBar = $('.slider-box div');
$innerBar.css('width', innerWidth + 'px');
console.log("Width should be: " + innerWidth + 'px');
}
然后我用 jQuery 调用每个函数:
$(document).ready(function() {
var $innerBar = $('.slider-box div');
$innerBar.each(function(index) {
var newWidth = $(this).attr("data-bar-width");
barGraph(newWidth, 267);
});
});
控制台日志显示 10 次,且宽度均合适。但是,所有样式都与最后一个宽度相同。
有人可以帮忙解释一下如何获得设置当前选定 div 宽度的函数吗?
提前非常感谢,
亚当。
最佳答案
让我们来分解一下
$(document).ready(function() {
var $innerBar = $('.slider-box div');
// going to call the barGraph function on each matching element
// so far, so good
$innerBar.each(function(index) {
var newWidth = $(this).attr("data-bar-width");
barGraph(newWidth, 267);
});
});
然后在barGraph
function barGraph(innerWidth, barWidth) {
innerWidth = parseInt(innerWidth) * .01 || .50;
barWidth = parseInt(barWidth) || 267;
// find percentage of total width
var innerWidth = Math.floor(innerWidth * barWidth);
// getting all the matching elements (again)
var $innerBar = $('.slider-box div');
// setting the width of each matched element to
// the innerwidth calculated in this barGraph call.
$innerBar.css('width', innerWidth + 'px');
console.log("Width should be: " + innerWidth + 'px');
}
因此,barGraph
函数会运行与 $('.slider-box div')
中匹配的元素一样多的次数,但每次运行都会设置宽度所有匹配的元素。实际上,最后一次运行会将所有匹配元素的宽度设置为上次运行时计算出的 innerWidth
值。这是您希望发生的事情吗?
更有可能的是这样的事情
$(function() {
var $innerBar = $('.slider-box div');
// going to call the barGraph function on each matching element
// so far, so good
$innerBar.each(function(index) {
var bar = $(this),
newWidth = bar.attr("data-bar-width");
barGraph(bar, newWidth, 267);
});
function barGraph(bar, innerWidth, barWidth) {
innerWidth = parseInt(innerWidth, 10) * .01 || .50;
barWidth = parseInt(barWidth, 10) || 267;
innerWidth = Math.floor(innerWidth * barWidth);
bar.css('width', innerWidth + 'px');
console.log("Width should be: " + innerWidth + 'px');
}
});
如果 barGraph 函数不在 each
调用之外使用,那么我可能倾向于将函数体移动到传递给 each
的匿名函数内部或修改barGraph 函数是传递给每个 i.e. 的函数
$(function() {
$('.slider-box div').each(barGraph);
function barGraph(index, element) {
var bar = $(this),
newWidth = bar.attr("data-bar-width");
newWidth = parseInt(newWidth , 10) * .01 || .50;
newWidth = Math.floor(innerWidth * 267);
bar.css('width', newWidth + 'px');
console.log("Width should be: " + newWidth + 'px');
}
});
关于javascript - 功能是设置全部而不是每个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8811565/