2011-05-23 92 views
1

我有這個HTML頁面,我嘗試計算一輛汽車的打撈價格,我有一個inputfield與它的清單價格,以及一個按鈕,我可以動態地添加不同的打撈價格計算javascriptjQuery動態添加組件的嵌套選擇器

List price: <input type="text" id="listprice"/> 
    <input type="button" id="addpricecalc" value="Add"/> 
    <div class="pricecalc"> 
    <input type="text" class="salvagepricepercent"/> 
    <input type="text" class="salvageprice"/> 
    </div> 

所以每次按下按鈕時,類pricecalc的另一個div被添加,具有相同的組件。

我遇到的問題是試圖使salvagepricepercent和salvageprice字段相互依賴(每當一個更改,其他更改相應),與動態添加的div。當我只使用1個pricecalc時它工作正常,但是當我添加一秒鐘時它不再工作。

我該如何繼續使用jQuery來解決這個問題。我認爲,我必須使用嵌套選擇器,並將jquery計算函數分配給動態添加的組件。

回答

1

我建議你的方法是通過遍歷父,並從那裏尋找到動態變化的事件添加到輸入字段(.live是爲這個偉大的),在事件處理程序,你可以找到匹配字段兄弟姐妹的班級名稱。

您可以使用像這樣(沒有測試過,可能有一些語法被打破):

$(".salvagepricepercent").live("change",function() { 
var priceField = $(this).parent().find(".salvageprice"); 
//do your calculation here, something like: 
    priceField.val(priceField.val() * $(this).val()/100); 
}); 

和周圍的其他方法...