我试图隐藏屏幕中的所有图像,并在向左或向右单击时一次显示一个图像。
我知道你可以通过在CSS中使用img { display:none; }
来隐藏所有内容,但我是这样做的(因为我可能想对每个对象应用不同的样式):
$("img[class*='wp-image']").get().each(function(){
$(this).css("display","none");
});
我知道这可能会返回一个错误,因为我认为你不能以这种方式将.each()
与.get()
一起使用,它确实这样做了,在控制台上引用了Uncaught TypeError: Object [object Array] has no method 'each'
。
如何实际使用.get
、.each
、.css
,并分别对它们应用CSS样式?
您根本不需要使用.each()
。大多数jQuery方法都可以应用于集合,并自动分配到所有选定的元素:
$("img[class*='wp-image']").css("display", "none");
如果您确实需要使用.each
,也许是因为您需要对每个元素进行有条件的更改,您可以将其直接应用于集合:
$("img[class*='wp-image']").each(function(){
$(this).css("display","none");
});
这里不需要.get()
方法。您可以隐藏所有图像:
$("img[class*='wp-image']").each(function (index) {
// Hide all the images
$(this).css("display", "none");
});
并将CSS样式分别应用于它们中的每一个,如:
$("img[class*='wp-image']").each(function (index) {
// Check the index of the items
if (index == 0) {
// Apply specific style to first element
$(this).css("border", "2px solid red");
} else if (index == 1) {
// Apply specific style to second element
$(this).css("border", "2px solid green");
}
// similarly you can apply styles to each of them individually
});
FIDDLE演示
您可以完全删除get和$each方法
$("img[class*='wp-image']").css("display","none");
我认为你可以在没有get()的情况下完成
$("img[class*='wp-image']").each(function(){
$(this).css("display","none");
});
您也可以使用hide()