在下拉菜单中单击p元素后获取图像的id

Get id of image after click on p element in drop down menu

本文关键字:获取 图像 id 元素 下拉菜单 单击      更新时间:2023-09-26

我有这样的代码:

<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时,我需要获得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和一些问题,但这取决于兄弟姐妹的关系。

您可以使用.closest()遍历到td,然后找到图像

对于集合中的每个元素,通过测试元素本身并遍历其在DOM树中的祖先,获得与选择器匹配的第一个元素。

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

也可以使用

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

试试这个

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

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

获取img元素

你可以试试:

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

试试这个:

你可以先搜索父'td',然后你可以找到图像id。

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

试试这个

$("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>