我有以下 HTML 代码,我已将背景颜色设置为红色 #list 。如果 li 的数量超过 5,我想将背景更改为蓝色。请协助
<html>
<head>
<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var len= $("#list li").size();
if(len>5){
// i need the code to style the #list here if number of li is more than 5, say background to blue
}
});
</script>
</head>
<body>
<ul id="list" style="background:red; width:300px;height:300px;">
<li>Image 1</li>
<li>Image 2</li>
<li>Image 3</li>
<li>Image 4</li>
<li>Image 5</li>
<li>Image 6</li>
<li>Image 7</li>
<li>Image 8</li>
<li>Image 9</li>
<li>Image 10</li>
</ul>
</body>
</html>
最佳答案
您需要使用 .length
而不是 size()
。
var len= $("#list li").length;
if(len>5){
$("#list").css("background-color","blue"); //use .css() to change the background color
}
关于javascript - 根据条件使用 jquery 进行样式设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21594626/