2012-01-28 3 views
0

が、私はこのマークアップ(すべてunneccesary情報を削除)オブジェクトのtext()をDOMツリーの上に移動していますか? - jQueryの

<li> 
<a></a> 
<strong class="listingAmount">1</strong> 
<strong class="listingPrice">10</strong> 
<form class="marketListing"> 
<select> 
</select> 
<input /> 
</form> 
</li> 

を持っている私はjqueryの内選択ボックスのchange event.listingAmount.listingPriceの値を取得しようとしています。私は.parent().prev().closest()など多くの方法を試してみましたが、それを得ることはできません!

私のjqueryのは、これまでのところ、

$('.marketListing select').change(function() { 
    var price = $(this).parent().prev('.listingPrice').text(); 
    var amount = $(this).parent().prev('listingAmount').text(); 
    alert(price); 
    alert(amount); 
}); 

にはどうすれselectに、以前のある私が欲しいの値を得ることができますか?

おかげ

答えて

2

あなたが探している機能はprevAllないprevです。 prev関数は直前のノードのみを検索し、prevAllはすべての以前のノードを検索します。ここでは機能しフィドルにだ

フィドル:私はおそらく私が持っているだろうとそう<li>上のクラスを置くところhttp://jsfiddle.net/UasBq/

$('.marketListing select').change(function() { 
    var price = $(this).parent().prevAll('.listingPrice').text(); 
    var amount = $(this).parent().prevAll('.listingAmount').text(); 
    alert(price); 
    alert(amount); 
}); 
+0

ありがとうございました! –

0

コンテナを見つけることが知られており、簡単に、そしてあなたが<li>に上がると、あなたが興味のあるものを見つけるために下に戻ってくる:

<ul> 
    <li class="container"> 
     <!-- ... --> 
    </li> 
</ul> 

そしてclosestfindの単純な組み合わせは、あなたが欲しい欲しい取得します。

$('select').change(function() { 
    var $cont = $(this).closest('.container'); 
    var amount = $cont.find('.listingAmount').text(); 
    var price = $cont.find('.listingPrice').text(); 
    // ... 
}); 

デモ:http://jsfiddle.net/ambiguous/kAejF/

prevprevAllがあなたのjQueryのは非常に緩く、あなたのHTMLと結合されていることである使用しようとしている以上、このことの利点:あなただけの単純な封じ込めを必要とする、ネスティングや内部構造が重要ではありません。

0

私はあなたが近くにいると思う:最初の親のFORM要素を見つけ、選択から、

$('.marketListing select').change(function() { 
    var price = $(this).parents('form').prevAll('.listingPrice:first').text(); 
    var amount = $(this).parents('form').prevAll('.listingAmount:first').text(); 
    ... 
    ... 
}); 

この意志:

$('.marketListing select').change(function() { 
    var li = $(this).closest('li'); 

    var price = $('.listingPrice', li).text(); 
    var amount = $('.listingAmount', li).text(); 
    alert(price); 
    alert(amount); 
}); 
0

私はあなたのような何かをすると思います。次に、以前のすべての兄弟をスキャンし、最初の.listingPrice(および.listingAmount)を探します。

私は以下を使用します:フォームに兄弟である複数の.listingPriceクラスがある場合は、まず使用します。あなたが入れ子になったフォーム要素を持っていれば、あなたはもっと大きな問題を抱えているので、私は最初に両親(フォーム)に追加しませんでした:P

関連する問題