3 回答

TA貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超17個(gè)贊
當(dāng)您引用一個(gè)元素時(shí),它不會(huì)一直尋找代碼運(yùn)行后添加的新元素。所以它不會(huì)定位動(dòng)態(tài)創(chuàng)建的輸入。
您需要?jiǎng)?chuàng)建元素并在該元素上使用 inputFilter。
$(".intTextBox").inputFilter(function(value) {
return /^-?\d*$/.test(value);
});
$('#add').click(function(e){
var newInput = $('<input name="intTextBox" class="intTextBox">');
newInput.inputFilter(function(value) {
return /^-?\d*$/.test(value);
});
$('#generate').append(newInput);
}
刪除代碼重復(fù)
function addFilter (elems) {
elems.inputFilter(function(value) {
return /^-?\d*$/.test(value);
});
}
addFilter($(".intTextBox"));
$('#add').click(function(e){
var newInput = $('<input name="intTextBox" class="intTextBox">');
addFilter(newInput);
$('#generate').append(newInput);
}

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超8個(gè)贊
下面的代碼將您的 ID 隨機(jī)化為新元素以避免沖突(不是完美的解決方案;只是該示例的變通方法),然后在新元素上應(yīng)用過濾器。
(function($) {
$.fn.inputFilter = function(inputFilter) {
return this.on("input keydown keyup mousedown mouseup select contextmenu drop", function() {
if (inputFilter(this.value)) {
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (this.hasOwnProperty("oldValue")) {
this.value = this.oldValue;
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
} else {
this.value = "";
}
});
};
}(jQuery));
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
// Para números enteros
$(".intTextBox").inputFilter(function(value) {
return /^-?\d*$/.test(value);
});
$('#add').click(function(e) {
let randomId = "intTextBox_" + getRandomInt(100000);
$('#generate').append(`<input id="${randomId}" class="intTextBox">`);
$(`#${randomId}`).inputFilter(function(value) {
return /^-?\d*$/.test(value);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="add">ADD</button>
<div id="generate">
<input id="intTextBox" class="intTextBox">
</div>

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超9個(gè)贊
使用已連接的驗(yàn)證方法追加 DOM 元素
$('#add').click(function(e){
$('#generate').append('<input id="intTextBox"
class="intTextBox">').inputFilter(function(value) {
return /^-?\d*$/.test(value);
});
}
);
添加回答
舉報(bào)