jQuery .on('change')不会为动态添加的元素触发 [英] Jquery .on('change') not firing for dynamically added elements

查看:487
本文介绍了jQuery .on('change')不会为动态添加的元素触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个具有以下结构的页面

So I've got a page with the following structure

<div class="editCampaignBanner">
    <div>
    <hr>
    <label for="file">Upload a new image</label>
    <input id="file" type="file" name="file" class="valid">
    <label for="NewImageURLs">Link URL (Optional)</label>
    <input id="NewImageURLs" type="text" value="" name="NewImageURLs">
    <hr>
    </div>
</div>

我这样写了一些jquery:

and I've written some jquery thus:

$('div.editCampaignBanner input:file').on('change', function () {
        var value = $(this).val();
        var div = $(this).parent();
        var html = '<div>'+ div.html() + '</div>';
        if (value.length > 0) {
            div.after(html);
        }
        else if ($(this) > 1) {
            div.remove();
        }
    });

因此,当我在文件中输入元素时,它会在上一个元素下生成一个div:

so when I enter an element into the file it generates a div under the previous one:

    <div class="editCampaignBanner">
        <div>
        <hr>
        <label for="file">Upload a new image</label>
        <input id="file" type="file" name="file" class="valid">
        <label for="NewImageURLs">Link URL (Optional)</label>
        <input id="NewImageURLs" type="text" value="" name="NewImageURLs">
        <hr>
        </div>
        <div>
        <hr>
        <label for="file">Upload a new image</label>
        <input id="file" type="file" name="file" class="valid">
        <label for="NewImageURLs">Link URL (Optional)</label>
        <input id="NewImageURLs" type="text" value="" name="NewImageURLs">
        <hr>
        </div>
    </div>

但是现在,尽管使用.on()注册了事件,但div中输入的第二个文件仍不会触发该事件.我想念什么?

But now, despite the event being registered using .on() the second file input in the div does not fire the event. What am I missing?

推荐答案

替换

$('div.editCampaignBanner input:file').on('change', function () {

通过

$('div.editCampaignBanner').on('change', 'input:file', function () {

这篇关于jQuery .on('change')不会为动态添加的元素触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆