jQuery - 参考附近的元素

djt*_*djt 0 html javascript jquery jquery-selectors

当'product-input'的值发生变化时,我希望'product-total'更新.我有活动,但我似乎无法提及'product-total'.

这是HTML:

<div class='product'>
    <h2>Photo Prints up to 5” x 7”</h2>
    <div class='product-total'></div>
        <div class='choices'>
        <input type='text' class='raw standard product-input'  />
    </div> <!-- END Choices -->

    Standard: <input type='radio' class='quality standard' value='standard' />
    Full: <input type='radio' class='quality full' value='full' />

</div> <!-- END Product -->
Run Code Online (Sandbox Code Playgroud)

和jQuery:

jQuery('input.product-input').change(function() {
        jQuery('div.product-total', jQuery(this).parent('div.product')).html(total);

    });
Run Code Online (Sandbox Code Playgroud)

gdo*_*ica 5

更换:

jQuery(this).parent('div.product')
Run Code Online (Sandbox Code Playgroud)

附:

jQuery(this).closest('div.product')
Run Code Online (Sandbox Code Playgroud)
  • parent 仅上升一级.
  • closest 直到它找到第一场比赛.

完整代码:

jQuery(this).closest('div.product').find('div.product-total').html(total);
Run Code Online (Sandbox Code Playgroud)

find比上下文选择器更好,因为实际上find是上下文选择器使用的,所以你可以在第一时间使用它并保存该行程.