簡體   English   中英

從父div更改子img元素的樣式?

[英]change style of child img element from parent div?

所以我有

<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'

我以為兩個都應該返回相同的對象,但是顯然第二個甚至都不返回元素對象,有什么想法嗎? 謝謝..

使用數組表示法將提取DOMElement而不是jquery對象!
因此,您不能在提取的元素上使用jquery。

嘗試使用.first()

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

:eq()選擇器:

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

當您收到錯誤消息時,通常是由於這種問題。

使用[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"); 
});

$("#image_container").children("img")[0]是一個DOM元素,而不是jQuery對象,因此不能使用jQuery方法。

試試$("#image_container").children("img").first()

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

或更好:

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

發生錯誤是因為此行返回HTML元素,並且它沒有被jQuery包裝

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

如果您將行更改為始終使用jQuery,它將看起來像這樣

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

並且像魅力一樣工作;-)

您可以使用nth-child()選擇器,只記得它是一個以1為底的數組,這與大多數以0為底的JavaScript數組不同:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM