2012-03-19 83 views
1

所以我有从父div改变儿童img元素的风格?

<div style="width:500px;" id="image_container"> 
    <img src="1.jpg" id="test"alt="test" /> 
    <img src="2.jpg" alt="test" /> 
</div> 

,然后我有一个简单的JavaScript

$(document).ready(function(){ 
    $("#test").css("display","none"); 
    $("#image_container").children("img")[0].css("display","none"); 
}); 

的JavaScript的第一行的作品完美,但第二线返回低于

Uncaught TypeError: Object #<HTMLImageElement> has no method 'css' 

我以为例外都假设返回相同的对象,但显然第二个甚至没有返回一个元素对象,任何想法? 感谢..

+0

您正在将jQuery与本机DOM对象操作混合在一起,我们当然可以帮助您完成所描述的语法,但是您能告诉我们您真正想要完成的任务吗? – n8wrl 2012-03-19 20:20:21

+0

我基本上想要遍历图像并改变它们的风格......我认为@Jeff B下面写了我正在寻找的内容,即eq(x)函数.. – bernabas 2012-03-19 20:34:31

回答

1

使用[0]访问DOM对象,而不是jQuery对象。这会导致错误,因为DOM没有定义jQuery函数。

.eq(x).first()/.last()等返回jQuery对象。

试试这个:

$(document).ready(function(){ 
    $("#test").css("display","none"); 
    $("#image_container").children("img").eq(0).css("display","none"); 
}); 
0

尝试$("#image_container").children("img").first().css("display","none");

或更好:

$("#image_container img").first().hide();

1

$("#image_container").children("img")[0]是一个DOM元素,而不是一个jQuery对象,所以你不能使用jQuery的方法。

尝试$("#image_container").children("img").first()代替。

4

使用数组符号抽取DOMElement,而不是jquery对象!
所以你不能在提取的元素上使用jquery。

尝试使用.first()

$("#image_container").children("img").first().css("display","none"); 

还是:eq()选择:

$("#image_container").children("img:eq(0)").css("display","none"); 

当你得到你得到错误信息,这是因为这类问题通常。

0

错误发生职高此行返回HTML元素,如果你改变使用jQuery所有的时间就应该是这样的

$("#image_container img").first().css("display","none"); 
行就不会被jQuery的

$("#image_container").children("img")[0].css("display","none"); 
// You get an array of HTML elements and you will work with the first one. 

包裹

和工作就像一个魅力;-)

0

你可以使用nth-child()选择器,只是记住它是一个基本1数组不像大多数基于0的JavaScript数组:

$(function(){ 
    $('#image_container:nth-child(1)').css('display','none'); 
});