簡體   English   中英

單擊按鈕時未觸發更改事件

[英]Change event not firing on button click

當數量發生變化時,我正在使用腳本將源元素的文本復制到目標元素,通過箭頭鍵或單擊 + 或減號按鈕。

 $(':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>

如果我單擊輸入框並使用箭頭鍵,它可以正常工作,但是當我單擊加號或減號鍵時,目標值比源值低一。

任何幫助表示贊賞。

您沒有任何代碼在單擊按鈕時運行,因為按鈕沒有通過用戶輸入更改的值,也沒有響應keyup事件。 你說你已經讓按鈕工作了,但如果是這樣的話,你有更多的代碼是你沒有發布的。

請參閱下面的內聯評論:

 $(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