[英]Jquery - get element closest to clicked button in container
我使用 php 從 mongodb 數據庫中獲取數據並將其顯示為 html 元素。 使用 jquery 我想單擊我擁有的每個項目上的按鈕並獲取單擊項目的元素標題並 console.log 它。
這是我的產品容器,其中包含已創建的元素。
<div class="category__container">
<div class="category__center">
<?php
//get products and display them as html
$cursor = $collection->find();
foreach ($cursor as $doc){
echo
" <div class= 'product category__products'>
<div class='product__header'>
<img src = ".$doc["image"]." />
</div>
<div class= 'product__footer'>
<h2> ".$doc["title"]." </h2>
<div class= 'product__price'>
<h4> $".$doc["price"]." </h4>
</div>
<button type='button' class='product__btn'>Add To Cart</button>
</div>
</div>
";
}
?>
</div>
</div>
我的 jquery 事件准備就緒:
$('.category__center').on('click' , '.product__btn' ,(e)=>{
//this is where I want to get the <h2> title from '.product__footer'
})
我會很感激你的幫助。
您可以使用closest(".product__footer").find("h2")
來獲取h2
標簽值。
演示代碼:
$('.category__center').on('click', '.product__btn', (e) => { //get closest product footer then h2 text console.log($(e.target).closest(".product__footer").find("h2").text()) console.log($(e.target).closest(".product").find('img').attr('src')) })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="category__container"> <div class="category__center"> <div class='product category__products'> <div class='product__header'> <img src="abc.png" /> </div> <div class='product__footer'> <h2> Abs12</h2> <div class='product__price'> <h4>123 </h4> </div> <button type='button' class='product__btn'>Add To Cart</button> </div> </div> <div class='product category__products'> <div class='product__header'> <img src="deded.png" /> </div> <div class='product__footer'> <h2> Abcd </h2> <div class='product__price'> <h4>12 </h4> </div> <button type='button' class='product__btn'>Add To Cart</button> </div> </div> </div> </div>
對每個 product__btn 使用自定義屬性,例如 -
<button type='button' class='product__btn' data-product='".$doc["title"]."'>Add To Cart</button>
現在在 jQuery 的點擊事件中,使用 -
$('.category__center').on('click', '.product__btn',(e)=>{ var productName = $(this).attr('data-product'); })
$(document).on("click",".product__btn", function(){
let title = $(this).closest(".product__footer").find("> h2").text().trim();
console.log(title);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.