gpt4 book ai didi

javascript - jQuery 从具有相同类的不同 div 的元素中获取文本值

转载 作者:行者123 更新时间:2023-11-29 17:47:07 27 4
gpt4 key购买 nike

<div class="panel">
<div class="panel-heading item-name">T-shirt1</div>
<div class="panel-body"><img src="img/shirt1.jpg" class="img-responsive" alt="Image"></div>
<div class="panel-footer text-center">
<h5>PRICE: <span class="old-price">$15.32</span></h5>
<h4>$17.56</h4>
<button type="button" class="btn btn-danger add-to-cart">Add to cart</button>
</div>
</div>
<div class="panel">
<div class="panel-heading item-name">T-shirt2</div>
<div class="panel-body"><img src="img/shirt2.jpg" class="img-responsive" alt="Image"></div>
<div class="panel-footer text-center">
<h5>PRICE: <span class="old-price">$21.67</span></h5>
<h4>$23.15</h4>
<button type="button" class="btn btn-danger add-to-cart">Add to cart</button>
</div>
</div>
<div class="panel">
<div class="panel-heading item-name">T-shirt3</div>
<div class="panel-body"><img src="img/shirt3.jpg" class="img-responsive" alt="Image"></div>
<div class="panel-footer text-center">
<h5>PRICE: <span class="old-price">$16.69</span></h5>
<h4>$16.80</h4>
<button type="button" class="btn btn-danger add-to-cart">Add to cart</button>
</div>
</div>

我真正想要的是在单击“添加到购物车”按钮时检索每个项目名称的值。如果我点击第一个按钮,我应该得到 T-shirt1,第二个按钮应该提醒 T-shirt2,第三个按钮 => T-shirt3.

这是我的 jQuery 脚本。

<script>

$('.add-to-cart').click(function() {
var itemName = $('.item-name', this).text();
alert(itemName);
});
</script>

最佳答案

你可以试试这个:

$('.add-to-cart').click(function() {
var itemName = $(this).closest('.panel').find('.item-name').text();
alert(itemName);
});

closest 方法的使用:closest

关于javascript - jQuery 从具有相同类的不同 div 的元素中获取文本值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48253199/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com