2

HTML に次の div コレクションがあります。ユーザーの操作に応じて動的にレプリケートするように設計されています。

 <div class="bill-item">
<!-- Section for a single item -->
<div class="bill-item-img">
<!-- Section for Item pic -->
</div>
<div class="bill-item-description">
<!-- Section for Item description and pricing -->
<div class="bill-item-name">
<p class="bill-item-name-left">Normal Cofee</p><p class="bill-item-name-right">170.00</p>
<div class="clear"></div>
</div>
<div class="bill-item-price">
<span>170.00 USD</span>
</div>
    <div class="bill-item-amount">
<span>2</span>
</div>
</div>
<div class="bill-amount-selection">
<!-- Section where the increment & decrement of item amount goes -->
<a class="amount-increase" href="#"></a>
<a class="amount-decrease" href="#"></a>
</div>
</div>

これは、要素の HTML レンダリング イメージです。

ページ

請求項目金額のスパン値を増やすために、次のスクリプトを作成しました。

 $(".amount-increase").click(function(){
            x+=1;
            $(".bill-item-amount span").html(x);
        });

        $(".amount-decrease").click(function(){
            if(!x<=0){
                x-=1;
                $(".bill-item-amount span").html(x);
            }
        });

これはうまく機能しますが、両方のスパン要素の値を更新します。私が望むのは、クリックされた要素のイベントをキャッチし(今はそうしています)、それぞれのスパンのスパン値を増やすことです。javascript を使用して更新するスパンを除外するにはどうすればよいですか?

4

5 に答える 5

2

のようなもの$(this).parents('.bill-item').find('.bill-item-amount span')が正しい要素を選択する必要があります。
内部でコールバックthisが に割り当てられますeventSource

于 2013-04-09T09:10:13.763 に答える
1

要素に到達.bill-itemし、.bill-item-amount spanノードに移動するまで、クリックした要素から dom ツリーをたどる必要があります。

$(".amount-increase").click(function(){
    var $span = $(this).parent().parent().find(".bill-item-amount span");
    var x = $span.html();
    x+=1;
    $span.html(x);
});

$(".amount-decrease").click(function(){
    var $span = $(this).parent().parent().find(".bill-item-amount span");
    var x = $span.html();
    if(!x<=0){
         x-=1;
        $span.html(x);
    }
});
于 2013-04-09T09:09:23.457 に答える
0
 $(".amount-increase").click(function(){
        x+=1;
        $("use ur increase span id here").html(x); //
    });

    $(".amount-decrease").click(function(){
        if(!x<=0){
            x-=1;
            $("use ur decrease span id here").html(x);
        }
    });
于 2013-04-09T09:19:00.637 に答える
0

各関数内で、セレクターはドキュメント内の$(".bill-item-amount span")すべての<span>金額を検索します。jQuery またはプレーンな JavaScript を使用して、DOMをたどって正しいものを見つけることができます。<span>あなたはjQuery関数を使用しているようですので、私の答えもjQueryを使用しています。

<a>次のコードは、クリックされたオブジェクトのクラス名に基づいて量を増減する 1 つの関数に 2 つのアクションを結合します。return falseまた、ブラウザーがアンカーのhref="#"をたどらないように を追加しました。

$('.bill-amount-selection').on('click', 'a', function(){
    var change = this.className == 'amount-increase' ? 1 : -1
    var $amount = $(this).closest('.bill-item').find('.bill-item-amount span')
    var amount = parseInt($amount.html(), 10) + change
    $amount.html(amount < 0 ? 0 : amount)
    return false
});

の使用は.on()、jQuery v1.7+ が必要であることを意味します。必要に応じて、下位の jQuery バージョンで互換性のある関数を提供できます。

于 2013-04-09T09:29:09.310 に答える