1

顧客が数量を変更したり、必要な属性を選択したりすると、Web サイトの価格を更新する ajax モジュールがあります。入力ボックスに値が入力されるとすぐに、価格が更新されます。ユーザーがボックスをクリックして数量を入力するのではなく、値をインクリメントするための素敵な jQuery ボタンをいくつか追加することにしました。問題は、ボタンを作成するために使用するスクリプトが、入力フィールドの値を変更しても、価格の変更をトリガーしないことです。

私のスクリプトは次のとおりです。

<script language="javascript">
jQuery.noConflict();
jQuery(document).ready(function() {
jQuery("#cartAdd").prepend('<div class="dec button">-</div>');
jQuery("#cartAdd").append('<div class="inc button">+</div>');
jQuery(".button").click(function() {
var $button = jQuery(this);
var oldValue = $button.parent().find("input").val();

if ($button.text() == "+") {
var newVal = parseFloat(oldValue) + 1;
} else {
if (oldValue >= 1) {
var newVal = parseFloat(oldValue) - 1;
}
}
$button.parent().find("input").val(newVal);
});
});
</script>

価格アップデーターが入力フィールドの新しい値を認識するように、この関数を作成する方法はありますか?

4

4 に答える 4

2

ページが読み込まれた後に読み込まれる要素にはデリゲート関数を使用する必要があります

jQuery(document).on('click','.button',function(){
 //Code here
});

.on()のドキュメント

于 2013-03-01T13:15:51.440 に答える
1

「ライブ」について心配する必要がないようにイベント委任を使用することをお勧めします。起動する変更イベントを探している場合は、Tetaxaが言ったように手動で行う必要があります。このようなもの:

<script language="javascript">
  jQuery.noConflict();
  jQuery(document).ready(function() {
    var $cartAdd = jQuery('#cartAdd')
      , $quantity = $cartAdd.find('input')
      , $price = jQuery('#price');

    $cartAdd.prepend('<div class="dec button">-</div>');
    $cartAdd.append('<div class="inc button">+</div>');

    $cartAdd.click(function(evt) {
      var $incrementor = jQuery(evt.target)
        , quantity = parseInt($quantity.val(), 10);

      if($incrementor.hasClass('inc')) {
        quantity += 1;
      } else if($incrementor.hasClass('dec')) {
        quantity += -1;
      }

      if(quantity > 0) {
        $quantity.val(quantity).change();
      }
    });

    $quantity.change(updatePrice);

    function updatePrice() {
      var price = 15.50
        , quantity = parseInt($quantity.val(), 10);
      $price.text(quantity * price);
    }
  });

</script>

これが動作するコードを含むjsFiddleです。

編集:数量入力の変更イベントを処理するコードを追加しました。

編集2:問題が今何であるかがわかります。ソースを調べた後、テキスト入力のオンキーアップのみを探しているように見えるため、変更のトリガーは効果がありません。あなたの当面の問題を解決するために、私は上記を代用します:

      if(quantity > 0) {
        $quantity.val(quantity).change();
      }

代わりに

      if(quantity > 0) {
        $quantity.val(quantity);
        xhr.getPrice();
      }
于 2013-03-01T13:46:07.097 に答える
1
try this 1...

    jQuery(".button").on('click',(function() {
    var $button = jQuery(this);
    var oldValue = $button.parent().find("input").val();

    if ($button.text() == "+") {
    var newVal = parseFloat(oldValue) + 1;
    } else {
    if (oldValue >= 1) {
    var newVal = parseFloat(oldValue) - 1;
    }
    }
    $button.parent().find("input").val(newVal);
    });
于 2013-03-01T13:15:57.103 に答える
0

正しく理解していれば、入力フィールドの値は変更されましたが、トリガーされない変更イベントにイベントハンドラーがアタッチされていますが、これは正しいですか?その場合は、コードを次のように変更して、イベントを手動でトリガーします。

$button.parent().find("input").val(newVal).change();
于 2013-03-01T13:25:22.320 に答える