简体   繁体   English

单击父级时如何获取子级名称

[英]How to get the child name when I click the parent

I have many search result like this:我有很多这样的搜索结果:

<div id="product-button">
    <p id="product-id">id</p>
    <p id="product-name">name</p>
</div>
<div id="product-button">
    <p id="product-id">id</p>
    <p id="product-name">name</p>
</div>

etc etc

I need to get the text of the name and id of product that I click我需要获取我单击的产品名称和 ID 的文本

my shut but print <empty string> in the console:`我关闭但在控制台中打印<empty string> :`

$(document).on('click', '#product-button', function(){

  console.log($(this).closest('#product-button').children('#product-name').text());

});

The id of an element has to be unique.元素的 id 必须是唯一的。 Replace them with classes.用类替换它们。

<div class="product-button">
    <p class="product-id">id_1</p>
    <p class="product-name">name_1</p>
</div>
<div class="product-button">
    <p class="product-id">id_2</p>
    <p class="product-name">name_2</p>
</div>

$(this) is ('#product-button') so no need for it: $(this) 是 ('#product-button') 所以不需要它:

$(document).on('click', '.product-button', function(){

  console.log($(this).children('.product-name').text());

});

 $(document).on('click', '.product-button', function(){ console.log(`${$(this).children('.product-name').text()} ${$(this).children('.product-id').text()}`); });
 <div class="product-button"> <p class="product-id">id_1</p> <p class="product-name">name_1</p> </div> <div class="product-button"> <p class="product-id">id_2</p> <p class="product-name">name_2</p> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 通过单击父名称jsTree获取子节点 - Get child node by click on parent name jsTree 当我单击其任何一个子元素时,如何获取最顶层的父 ID? - How to get top most parent Id when I click on any one of its child element? 当我单击父 div 时如何切换子 div - How to toggle a child div when i click on a parent div 当我们单击子复选框时,如何获取父母的父母ID - How to get the parent id of the parent when we click on the child check box 如果单击 document.body.addEventListener 中的任何子项、孙子项(以及更深层次),如何点击父标记 - How to get click on parent tag if I click on any child, grandchild (and deeper) in document.body.addEventListener 单击父级时如何获取儿童 ID? - How to get children id when I click the parent? 从子级拖动到父级时如何防止父级单击事件 - How to prevent parent click event when dragging from child to parent 单击子控件单击时如何停止父gridview事件? - How to stop parent gridview event when click on child control click? 每当我点击jQuery中的一个子li时,如何获取父li? - How do I get the parent li everytime I click one of the child li in jQuery? 单击元素父JQuery外部的div时如何获取元素子项中的值 - How to get the value in element child when click a div outside element parent JQuery
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM