jQuery .find() 不适用于动态添加的元素

时间:2021-04-05 13:13:07

标签: javascript jquery

我有一个操作类名的函数 -

function detectInputs() {
    $(".myform").find("input.input-text").filter(function() {
        if( $(this).val().length === 0 ) {
            $(this).closest( "p.form-row" ).removeClass("parent-filled");
            $(this).closest( "p.form-row" ).addClass("parent-empty");
        } else {
            $(this).closest( "p.form-row" ).removeClass("parent-empty");
            $(this).closest( "p.form-row" ).addClass("parent-filled");
        };
    });
}

但它只适用于页面加载时已经存在的元素。可以动态添加更多 p.form-row 元素。我知道 .on(),但不确定它会在何处与此功能集成。

2 个答案:

答案 0 :(得分:0)

可能是因为您在添加元素之前调用了该函数。尝试在您动态添加元素时调用它,它会正常工作。

截至您的代码:-

    function detectInputs() {
        $("body").find("input.input-text").filter(function() {
            if( $(this).val().length === 0 ) {
                $(this).closest( "p.form-row" ).removeClass("parent-filled");
                $(this).closest( "p.form-row" ).addClass("parent-empty");
            } else {
                $(this).closest( "p.form-row" ).removeClass("parent-empty");
                $(this).closest( "p.form-row" ).addClass("parent-filled");
            }
        });
    }
    
  

$("button").on( "click", function() {
  $("p").last().after('<p class="form-row"><input class="input-text" type="text"></p>');    
  detectInputs();
});

答案 1 :(得分:0)

在添加新元素“p.form-row”后触发事件并使用“on”绑定事件侦听器,其中回调将是您的函数“detectInputs”