Using a class name in jQuery's .closest()

后端 未结 4 494
长情又很酷
长情又很酷 2020-12-25 12:16

I\'m attempting to do some calculations for a \"running total\", this is my code:

$(\'.quantity_input\').live(\'change\',function(){         
                       


        
相关标签:
4条回答
  • 2020-12-25 12:49

    You don't need to use find. closest takes a context argument. that helps you narrow down the field of search. You should use that.

    0 讨论(0)
  • 2020-12-25 12:52

    I wouldn't use .find(). I'm guessing it will probably be a bit more efficient to traverse up to the closest <td> and get the sibling <td> with the .cost_of_items class using jQuery's .siblings() method.

    $(this).closest('td').siblings('.cost_of_items');
    

    EDIT: To clarify, here's the markup from the .append():

    <tr class="tableRow">
         <!-- NOTE THAT THE CLOSING </td> IS MISSING FOR THE FIRST <td> -->
        <td><a class="removeItem" href="#"><img src="/admin/images/delete.png"></img></a>
        <td class="om_part_no">' + omPartNo + '</td>
        <td>' + supPartNo + '</td>
        <td>' + cat + '</td>
        <td class="description">' + desc + '</td>
        <td>' + manuf + '</td>
        <td>' + list + '</td>
        <td>' + disc + '</td>
         <!-- TRAVERSE TO HERE -->
        <td>
           <p class="add_edit">Add/Edit</p>
            <!-- START HERE -->
           <input type="text" class="quantity_input" name="quantity_input" />
        </td>
        <td class="price_each_nett price">' + priceEach + '</td>
         <!-- SIBLING IS HERE -->
        <td class="cost_of_items"></td>
        <td><p class="add_edit">Add/Edit</p><input type="text" class="project_ref_input" name="project_ref_input" /><p class="project_ref"></p></td>
    </tr>
    
    0 讨论(0)
  • 2020-12-25 12:57

    You need to find the .cost_of_items in the <tr> containing this:

    $(this).closest('tr').find('.cost_of_items')
    
    0 讨论(0)
  • 2020-12-25 13:00

    Closest will find the closest ancestor (parent, grandparent), but you will then need to do a find in order to find the correct element to update. For example, if you have an element in a table row and you need another element in that same row:

    $('.myElement').closest('tr').find('.someOtherElement');
    

    Edit:

    In your case, you will want

    $(this).closest('tr').find('.cost_of_items').text(totalTotal.toFixed(2));
    
    0 讨论(0)
提交回复
热议问题