2012-09-06 61 views
-3

我想用jquery查找父div內的圖像。我不知道什麼是最好的和快速的方式來找到它。如何選擇父div的內容

html 

more divs..and all generated dynamically.. 
<div> 
other dynamically generated image... 

<img src='haha1.jpg' /> 
<img src='haha2.jpg' /> 
</div> 

<div>div 2</div> 
<div>div 3</div> 
<div>div 4</div> 
<div>div 5</div> 

more divs.... 

<div> 
<button id='btn'/> 
</div> 


$('#btn').click(function(){ 

    //I have to change image source by using parent() method.... 

}) 

感謝您的幫助!

+0

......究竟改變什麼形象的'href',你在那裏 –

+0

有2個(及以上)和......你不能只是一個'id'或'class'添加到DIV擁有圖像? –

回答

0

如果您的按鈕可以有一個ID ...

<div id="images"> <!-- add an ID here too --> 
    <img src='haha1.jpg' /> 
    <img src='haha2.jpg' /> 
</div> 

的jQuery:

var source = 'folder_name/'; 

$('#btn').click(function(){ 
    $('#images').find('img').each(function(){ 
     $(this).attr('src', source+this.src); 
    }); 
}); 
0

如果我理解正確,您希望能夠更改特定div內的圖像的src。如果是這種情況,請查看此代碼中的選項是否可以提供幫助。

$('#btn').click(function(){ 

//I have to change image source by using parent() method.... 


$("#divId").children("img").attr("src", "newImgSource.jpg"); //this will probably change all the images int the div. 
$("#imgId").attr("src", "newImgSource.jpg");//this should change a specific image's src. 


}); 
0

http://jsfiddle.net/truuD/12/

我通常使用.prev()和.find()對於這樣的事情。不知道它是最快還是最好的方式,但它對我有用。

$("button").click(function(){    
    console.log($(this).parent("div").prev("div").find("img")); 
});​ 
+0

或者我猜你可以去: $(this).parent(「div」)。find(「div img」) – Hydrospanners