简体   繁体   English

单击按钮时未触发更改事件

[英]Change event not firing on button click

I'm using a script to copy the text of the source element to the target element when the quantity changes, either by arrow keys or clicking the + or minus buttons.当数量发生变化时,我正在使用脚本将源元素的文本复制到目标元素,通过箭头键或单击 + 或减号按钮。

 $(':input').on('change keyup', function() { var subtotal = $('.p.price.amount').text(); $('.price.amount').text(subtotal); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="quantity buttons_added"> <input type="button" value="-" class="minus"> <input type="number" name="quantity" value="1" title="Qty" class="input-text qty text"> <input type="button" value="+" class="plus"> </div> <p class="price">Subtotal <span class="amount">$12.50</span></p>

If I click in the input box and use the arrow keys, it works fine but when I click the plus or minus keys, the target value is one behind the source value.如果我单击输入框并使用箭头键,它可以正常工作,但是当我单击加号或减号键时,目标值比源值低一。

Any help appreciated.任何帮助表示赞赏。

You don't have any code that runs when the buttons are clicked because buttons don't have values that change through user input, nor do they respond to keyup events.您没有任何代码在单击按钮时运行,因为按钮没有通过用户输入更改的值,也没有响应keyup事件。 You say that you've got the buttons sort of working, but if that's the case, there's more code that you have that you didn't post.你说你已经让按钮工作了,但如果是这样的话,你有更多的代码是你没有发布的。

See the comments inline below:请参阅下面的内联评论:

 $(function(){ const basePrice = 12.5; // Set base price in code for easy changes later // Get references to elements you'll work with const $input = $("input.qty"); const $output = $('.price >.amount'); let qty = 1; // Keep track of qty // Initialize the output $($output).text(basePrice.toFixed(2)); // Handle changes made to the input type=number $('input.qty').on('input', function() { updateSubtotal(); }); // Handle clicks to the buttons $('.minus, .plus').on('click', function() { updateSubtotal($(this)); // Send clicked button reference to the function }); // Figure out the answer function updateSubtotal($btn){ // If a button got us here... if($btn){ // Increase or decrease the quantity based on which button was clicked $btn.val() === "+"? qty++: qty--; $input.val(qty); // Update the input type=number } qty = $input.val(); $output.text((basePrice * $input.val()).toFixed(2)); // Update the total } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="quantity buttons_added"> <input type="button" value="-" class="minus"> <input type="number" name="quantity" value="1" title="Qty" class="input-text qty text"> <input type="button" value="+" class="plus"> </div> <p class="price">Subtotal $<span class="amount"></span></p>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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