2015-06-02 21 views
0

點擊p元素上後,我有這樣的代碼:獲取圖像的ID在下拉菜單中

<table class="canToggle"> 
    <tr> 
     <td> 
      <div class="messagepop pop"> 
       <p class="selection">moss</p> 
       <p class="selection">gray</p> 
       <p class="close">Cancel</p> 
      </div> 
      <img src="images/gray.jpg" class="wide high image" id="x1y1" /> 
     </td> 
     ... 
    </tr> 
<table> 

當我點擊p S的一個,我需要得到img的ID,這樣我可以更改img src。我有這個jQuery:

var $selection = $(this).text(); 
$selection = "images/" + $selection + ".jpg"; 
// I need to populate the value of nextImgID for the next line 
$(nextImgID).attr('src', $selection); 

我想不通如何遍歷這個。我在這裏看過api和一些問題,但事情取決於兄弟姐妹關係。我將不勝感激任何幫助。

回答

3

您可以使用.closest()遍歷高達td然後找到圖像

對於組中的每一個元素,獲得通過自身測試元素,並通過其在祖先向上遍歷選擇相匹配的第一個元素DOM樹。

$(this).closest('td').find('img').attr('src', $selection); 

您還可以使用

$(this).closest('div').next('img').attr('src', $selection); 
+0

哇,成功了!謝謝!我正在全力以赴,從來沒有做到。 – pixelmeow

1

試試這個

$(document).on("click","selection",function(){ 
    var parent = $(this).parent(); // messagepopup div 
    var imgId = parent.next("img:first").attr("id"); 
}); 

您可以通過parent.next("img:first")

1

得到img元素你可以試試這個:

var image = $(this).parents('td').find('img').attr('src', 'url'); 
1

試試這個:

你可以先搜索父「TD」,然後你可以找到圖片ID。

$('p').click(function(){ 
var imageid =$(this).parents('td').find('img').attr('id'); 
//in image id you will get your image's id 
}) 
0

試試這個

$("p").click(function() { 
 
    alert($(this).parent().siblings().attr("id")); 
 

 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table class="canToggle"> 
 
    <tr> 
 
    <td> 
 
     <div class="messagepop pop"> 
 
     <p class="selection">moss</p> 
 
     <p class="selection">gray</p> 
 
     <p class="close">Cancel</p> 
 
     </div> 
 
     <img src="images/gray.jpg" class="wide high image" id="x1y1" /> 
 
    </td> 
 

 
    </tr> 
 
    <table>