[英]jQuery - How do I count children and apply percentage based width
How can I use jQuery to count the number of child elements (in this case list elements) inside div id #foo and then divide 100 / (# of counted child elements). 我如何使用jQuery来计算div id #foo中的子元素(在这种情况下为列表元素)的数量,然后除以100 /(已计数的子元素数量)。 The last step would be to apply that as a percentage based width 最后一步是将其应用为基于百分比的宽度
<style="width: Npx">
Where N = [100/(# of child elements)]? N = [100 /(子元素数)]?
$('someelement').width((100 / $('#foo').find('li').length));
您应该检查.length
是否为零,以避免被零除。
Try this(it takes care of case when there are not children in foo): 尝试以下操作(在foo中没有子节点的情况下,要注意大小写):
var el = $('#foo');
var len = el.children().length;
if(len > 0){
len = 100/len;
el.css("width", len + "px");
}
var count = $('#foo > *').length;
$('#bar').css({width:(100/count)+'%'});
<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.4.4.min.js"
type="text/javascript"></script>
</head>
<body>
<div id="foo">
<ul>
<li>Baseball</li>
<li>Basketball</li>
<li>Football</li>
<li>Soccer</li>
<li>Hockey</li>
</ul>
</div>
<script type="text/javascript">
$(function () {
var sWidth = "auto";
var liLength = $("#foo li").length;
alert(liLength);
if (liLength > 0) {
sWidth = (100 / liLength) + "%";
}
$("#foo").width(sWidth);
alert(sWidth);
});
</script>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.