简体   繁体   中英

target <td> in the same <tr>

I want to target <td class="total"> in the following structure:

<table class="table table-shopping-cart">

        <tbody>

            <tr>
                <td><div class="photo"></div></td>

                <td><div class="product"></div></td>

                <td style="text-align:center;">

                    <form action="/shoppingCart/261021" method="post" >
                    <div class="control-group quantity">
                          <div class="controls">
                              <a href="#" class="qty-btn qty-btn-minus">-</a><div class="qty-box">1</div><a href="#" class='qty-btn qty-btn-plus'>+</a>
                                 <span style="display:none;" class="maxQty">1</span>
                                 <select name="quantity" style="width: 60px" class="quantity" scliid="261021" id="quantity" >
<option value="1" selected="selected" >1</option>

</select>
                                 </div>
                            </div>
                        </form>
                </td>


                <td class="total">
                    <p style="margin-top:34px;">
                       $144.00
                    </p>
                </td>

            </tr>
            <tr>..</tr>
</tbody>
</table>

<script>  
$(document).ready(function () {
    $('.table-shopping-cart').delegate('.qty-btn-minus', 'click', function() {
        var $this = $(this);
        if(!$this.hasClass('blur')) {
            var $qtyBox = $this.parent().find('.qty-box');
            var $qtyBoxQty = 1*$qtyBox.text();
            var newVal = $qtyBoxQty;
            var form = $this.closest('form');
            alert($this.parent('tr').find('.total').text());
        });
});
</script> 

however, alert($this.parent('tr').find('.total').text());

returns undefined .

How to target following <td class="total"> to get '$144.00' ?

The .parent() method only selects the immediate parent, and in your case the immediate parent of the .qty-btn-minus anchor is a div element.

Use the .closest() method instead to navigate up through the DOM tree to the closest ancestor tr:

alert( $this.closest("tr").find(".total").text() );

(Also your if statement doesn't seem to have a closing } . You'll need to fix that or the script won't work at all.)

The easiest way is with the closest method:

console.log($this.closest('tr').find('.total p').text().trim());

The above will get the text value of the p tag within your total td. The output will yeild:

$144.00

You can simply select the td by the class and use the method .text()

$('td .total').text();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM