gpt4 book ai didi

jquery - 在 jQuery 中使用 'this'

转载 作者:行者123 更新时间:2023-12-01 01:21:59 24 4
gpt4 key购买 nike

有人可以帮我解决这个问题吗?

这是我的html

<div class="wrapper">
<div class="vacation" data-price="339.99">
<h3>British vacation</h3>
<p>£339.99 per ticket</p>
<p>Tickets:
<input type="number" class="quantity" value='1'>
<p/>
</div>
<p>Total price £: <span class="total">399.99</span></p>
</div>
<div class="wrapper">
<div class="vacation" data-price="449.99">
<h3>Spanish vacation</h3>
<p>£449.99 per ticket</p>
<p>Tickets:
<input type="number" class="quantity" value='1'>
<p/>
</div>
<p>Total price £: <span class="total">449.99</span></p>
</div>
<div class="wrapper">
<div class="vacation" data-price="559.99">
<h3>Italian vacation</h3>
<p>£559.99 per ticket</p>
<p>Tickets:
<input type="number" class="quantity" value='1'>
<p/>
</div>
<p>Total price £: <span class="total">559.99</span></p>
</div>

和 jQuery

$(document).ready(function(){
$('.vacation').on('keyup', '.quantity', function() {

var price = +$(this).closest('.vacation').data('price');
var quantity = +$(this).closest('.quantity').val();
var totalPrice = (price * quantity).toFixed(2);
$('.total').text(totalPrice);

});
});

问题是,当我计算其中一种度假选项的价格时,我已经更新了所有总价格。我尝试过:

$(this).closest('.total').text(totalPrice);

而且它不起作用。

请查看JS Bin

非常感谢!

最佳答案

问题是因为您选择了所有 .total 元素并在它们上设置了 text() 。相反,您可以使用 closest() 从引发事件的 .quantity 获取最近的父 .wrapper 元素,并使用 find( ) 其中的所有必需元素,如下所示:

$('.vacation').on('keyup input', '.quantity', function() {
var $wrapper = $(this).closest('.wrapper');
var price = parseFloat($wrapper.find('.vacation').data('price'));
var quantity = parseFloat($(this).val());
$wrapper.find('.total').text((price * quantity).toFixed(2));
});

另请注意,我连接了 input 事件,以涵盖单击 number 输入上的向上/向下箭头的用户。

关于jquery - 在 jQuery 中使用 'this',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38076818/

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