javascript - 验证新创建的输入

标签 javascript jquery

我正在使用带有动态创建输入的小型附件表单。

这些新输入是这样创建的:

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/

相关文章:

javascript - 无法从我的数组中删除偶数

java - REST 从 jQuery : Method Not Allowed error 中删除

javascript - 使用 XMLHttpRequest 和通用处理程序通过 FTP 下载 PDF 文件

JQuery 数据表隐藏 Bootstrap 下拉列表

javascript - jquery append() 在字符串位置

javascript - CSS 和 JS 更改按钮悬停时的 div 背景颜色?

具有编程样式的 Javascript 可编辑区域

javascript - scrolltop() 在 IE9 中根本不起作用

javascript - angular.js如何解析 View 内的变量数据

JavaScript 运行时错误 : "object doesn' t support property or method"in Internet Explorer