如何用jQuery替换这个for-each循环?
$(document).ready(function(){
hidebutton = $("#hideall");
hidebutton.click(function(){
for(i=1;i<=6;i++){
var countrylist = document.getElementById("Country-"+i);
countrylist.style.display = "none";
}
});
});HTML是
<input id="hideall" type="button" value='Hide Countries' /><br /><br />
<div id="Country-1">USA</div>
<div id="Country-2">UK</div>
<div id="Country-3">UAE</div>
<div id="Country-4">China</div>
<div id="Country-5">India</div>
<div id="Country-6">Japan</div>发布于 2011-05-19 01:47:39
编辑了你的jsfiddle,在评论中添加了jQuery foreach的例子。但是,这里不需要foreach,因为jQuery可以对集合进行操作。我也更改了你的HTML,你需要更好地对这些div进行分组:
<div id="Countries">
<div id="Country-1">USA</div>
<div id="Country-2">UK</div>
<div id="Country-3">UAE</div>
<div id="Country-4">China</div>
<div id="Country-5">India</div>
<div id="Country-6">Japan</div>
</div>
$(document).ready(function(){
hidebutton = $("#hideall");
hidebutton.click(function(){
$('#Countries div').hide();
// $('#Countries div').each(function(index, divElement) { ... });
});
});http://jsfiddle.net/nLfNj/3/
发布于 2011-05-19 01:45:14
有一个CSS3选择器可以满足您的需求
正如您可能知道的,无论浏览器是否支持CSS3选择器,jQuery都支持。
$('div[id^="Country"]').hide();发布于 2011-05-19 01:45:00
尝试:
hidebutton.click(function(){
$('[id^="Country-"]').hide();
});请注意,这也将隐藏所有碰巧以"Country-“开头的元素,您不想隐藏这些元素,但假设您没有任何这些元素,则此方法将起作用。
https://stackoverflow.com/questions/6048806
复制相似问题