[英]Count Dynamically created html elements with jquery
我正在計算當前文檔中有價值的輸入數量。 它工作正常,除了我動態添加更多輸入。 我無法達到價值觀。
例如我可能有
<input id="participant-1"/>
<input id="participant-2"/>
...
按鈕點擊后動態創建
<input id="participant-15" />
我會在for循環中得到每個值的值
for(var i =1 ; i <25; i++)
{
...$('input#participant-' + i).val();
}
現在,當我運行for循環來檢查每個輸入的值時,它只獲取未動態創建的輸入值。 我在這里看了其他問題,但我仍然看不到如何將.on()
到我想要完成的事情上。
新的關注問題好了,現在我認為這是我需要更多關於如何使用.on的澄清。
我在這里有一個jsfiddle: JsFiddle示例
我在哪里創建新元素和所有文本框的模糊我想計算有多少元素有價值並記錄它。 現在,它將使用靜態元素對blur事件做出響應。 它不適用於動態創建的元素
給它一個共同的類:
<input class="textbox" id="participant-1"/>
<input class="textbox" id="participant-2"/>
得到它像:
var values = [];
$('.textbox').each(function(){
values.push($(this).val());
});
console.log(values)
並回答編輯:
語法應該是: $(container_selector).on(event_type,target_selector,callback)
$('.name').on('blur', 'input', calculate_total);
還可以考慮使用CSS屬性選擇器。
http://www.w3.org/TR/CSS2/selector.html#attribute-selectors
$("input[id|=participant]").each(function(){
// something
});
使用類選擇器可以節省時間。
<input id="participant-1" class="participant"/>
<input id="participant-2" class="participant"/>
然后使用簡單的計數調用...
var count = $('.participant').length
alert ('You have ' + count + ' Counted Inputs');
//result is 2
希望你覺得這個有用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.