簡體   English   中英

動態添加輸入字段的鍵盤功能

[英]keyup function for dynamically added input fields

我試圖為動態添加的輸入字段實現keyup功能,但無法正常工作

HTML代碼

<table  border="1" id="table">
<colgroup>
<col width="100"/>
<col width="100"/>
</colgroup>
<tr>
<td style="text-align:center;">Activity</td>
<td style="text-align:center;">Time</td>
</tr>
<tr>
<td style="text-align:center;">
<select id="activity[]">
<option value="Working">Working</option>
<option value="Leave">Leave</option>
</select>
</td>
<td style="text-align:center;"><input style="width:35px;" type="text" class="text" maxlength="3" id="day1[]"/></td>
</tr>
</table>
<br><br>
<input type="button" value="+" id="plus" />

jQuery代碼

$("#plus").click(function(e){

$("#table").append("<tr><td style='text-align:center;'><select id='activity[]'><option value='Working'>Working</option><option value='Leave'>Leave</option></select></td><td style='text-align:center;'><input style='width:35px;' type='text' class='text' maxlength='3' name='day1' id='day1[]'/></td></tr>");
e.preventDefault();


});
$.each($('[id^=day1]'), function (i, item) {
         $("[id*='day1']").keyup(function () {
         if (this.value.match(/[^a-zA-Z.]/g)) {
            this.value = this.value.replace(/[^a-zA-Z.]/g, '');

        }
        });

        });

在這里查看演示

我在這里試過Soln 它也沒有用。

對於動態控件,您需要像這樣在文檔級別綁定事件:

$(document).on("keyup","[id*='day1']",function() { 
    // code goes here...
});

或者您也可以使用身體。

 $('body').on("keyup","[id*='day1']",function() { 
        // code goes here...
 });

事件處理程序僅綁定到當前選定的元素; 當您的代碼調用.on()時,它們必須存在於頁面上。 因此,在以下示例中,在生成代碼之前,#dataTable tbody tr必須存在。

如果要在頁面中注入新的HTML,則可以使用委托事件來附加事件處理程序,如下所述。

委派事件的優勢在於,它們可以處理來自后代元素的事件,這些事件在以后的時間添加到文檔中。 例如,如果該表存在,但是使用代碼動態添加了行,則將通過以下方式進行處理:

除了具有處理尚未創建的后代元素上的事件的能力外,委托事件的另一個優點是,當必須監視許多元素時,它們有可能大大降低開銷。 在其正文中具有1,000行的數據表上,第一個代碼示例將處理程序附加到1,000個元素。 委托事件方法(第二個代碼示例)將事件處理程序僅附加到一個元素(即tbody),並且事件僅需要起泡一個級別(從單擊的tr到tbody)。

嘗試這個

$.each($('[id^=day1]'), function (i, item) {
                 $(document).on('keyup', '[id*="day1"]',function () {
                 if (this.value.match(/[^a-zA-Z.]/g)) {
                    this.value = this.value.replace(/[^a-zA-Z.]/g, '');

                }
                });

DEMO

使用事件委托,元素的ID也必須是唯一的..因此,請從輸入字段中刪除ID

$(document).on('keyup', 'input[name="day1"]'function () {
    if (this.value.match(/[^a-zA-Z.]/g)) {
        this.value = this.value.replace(/[^a-zA-Z.]/g, '');
    }
});

您需要在plus click調用中添加處理程序。

您的其他代碼僅運行一次。

或看看livehttp : //api.jquery.com/live/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM