我正在使用带有动态创建输入的小型附件表单。
这些新输入是这样创建的:
function addAttachmentRow() {
var htmlRow = '<tr><td><input type="text" name="file_name[]"></td></tr>';
$("#attachment_list").append(htmlRow);
}
我正在尝试准备验证函数,但是这段代码:
$( document ).ready(function() {
$('input[name^="file_name"]').each(function() {
$(this).keydown(function(){
if ($(this).val().length < 2) {
$(this).css("background-color", "#FFCCCC");
$(this).css("border", "1px solid #665252");
$(this).css("color", "#B20000");
} else {
$(this).css("background-color", "#F5FFEB");
$(this).css("border", "1px solid #5CE65C");
$(this).css("color", "#145214");
}
});
});
});
但它仅适用于静态创建的第一个元素。它不会影响单击“addAttachmentRow”并添加新输入时创建的元素。
更改为
$('input[name^="file_name[]"]').each(function() {
也没有帮助,我只需要在输入名称中包含 [] 即可。
有什么想法吗?
提前致谢。
最佳答案
是的。它发生了。它不会选择具有该代码的元素。您将需要使用 $(document).on 方法而不是这个方法。
解决方案:
使用此代码
$(document).on('event', 'selector', function() {
// code
});
例如
$(document).on('each', 'input[name^="file_name[]"]', function() {
alert('Event fired!');
});
关于javascript - 验证新创建的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30755244/