0

我试图根据子元素的数量乘以每个子元素的恒定宽度来设置元素的宽度。我在页面上有多个这些元素,每个元素都有可变数量的子元素。

 $(".parent").css("width", ($(this).children().length * 150) + "px");

这似乎不像我预期的那样工作。我希望这能找到每个父类,然后根据每个元素各自子元素的数量计算宽度。

4

3 回答 3

2

也可以:

$(".parent").css("width", function () { 
   return ($(this).children().length * 150) + "px") 
});

jQuery.css()

于 2013-11-08T17:48:37.983 回答
1

它没有按预期工作,因为this它指向当前函数范围,而不是.parent. 为了实现您想要做的事情,您可以使用each.

$(".parent").each(function() {
    $(this).css("width", ($(this).children().length * 150) + "px");
});
于 2013-11-08T17:46:33.300 回答
1

这是代码运行的顺序,带有变量,因此可以清楚地说明顺序:

var $this = $(this);                // Wrap whatever the current value of `this`
                                    // is in a jQuery object; note this has
                                    // nothing to do  with ".parent"
var $children = $this.children();   // Get its children
var width = $children.length * 150; // Calculate the width
width = width += "px";              // Put a "px" on it (you don't need this)
var $parent = $(".parent");         // Find the element(s) with class "parent"
$parent.css("width", width);        // Apply the width to it

相反,您可能想要:

var $parent = $(".parent");
$parent.css("width", $parent.children().length * 150); // You don't need "px"
于 2013-11-08T17:50:07.897 回答