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

时间:2018-01-14 19:10:22

标签: javascript jquery html

<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,第三个按钮=&gt; T-shirt3

这是我的jQuery脚本。

<script>

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

2 个答案:

答案 0 :(得分:3)

你可以试试这个:

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

使用closest方法:closest

答案 1 :(得分:1)

从父母链中的单击按钮开始,直到找到.panel,然后在子树中向下,直到找到.item.name

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