.change() jquery 事件不适用于动态创建的输入元素

Avi*_*Avi 1 html javascript jquery

我的页面上有一个类型为“ file ”的输入。另外,我在页面上有一个按钮“添加输入”,它在页面上添加一个新的文件输入元素,当用户通过选择新文件更改任何这些输入的值时,我想运行一个函数。这是我的代码。

超文本标记语言

<div class="main">
    <div id="InpDiv">
        <input type="file" name="fname">
    </div>
</div>
<div>
    <button onclick="addInp()">Add Inputs</button>
</div>
Run Code Online (Sandbox Code Playgroud)

JS

// Function that is going to run after change in file input.

    $(document).ready(function(){
        $("input[name='fname']").each(function(){
            $(this).change(function(){
                alert('hello');
                
                // Do some work here.

            });
        });
    });


// Function that adds new file inputs.

    function addInp()
    {
        $('#InpDiv').clone().appendTo(".main");
    }
Run Code Online (Sandbox Code Playgroud)

现在的问题是 .change() 方法对于页面上已经存在的那些输入工作正常,但对于那些新创建的输入中的值更改则不起作用(此处不会提示“hello”消息) 。我在页面上已经存在了多个文件输入,并且 .change() 适用于所有这些输入,但它不适用于任何新创建的输入。

事件是否无法与页面上动态添加的元素一起使用?如果是这样,那么我将如何完成这项工作?

Mam*_*mun 5

尝试使用委托方法.on()。这将确保事件将附加到稍后添加到 DOM 的所有元素。

另外,我更喜欢使用输入事件而不是更改:

改变:

$(this).change(function(){
Run Code Online (Sandbox Code Playgroud)

到:

$('.main').on('input', this, function(){
Run Code Online (Sandbox Code Playgroud)

$(this).change(function(){
Run Code Online (Sandbox Code Playgroud)
$('.main').on('input', this, function(){
Run Code Online (Sandbox Code Playgroud)
$(document).ready(function(){
  $("input[name='fname']").each(function(){
      $('.main').on('input', this, function(){
          alert('hello');

          // Do some work here.

      });
  });
});


// Function that adds new file inputs.

function addInp()
{
  $('#InpDiv').clone().appendTo(".main");
}
Run Code Online (Sandbox Code Playgroud)