[英]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.