如何影响多个动态元素中的一个元素

how to influence the one element of the plurality of dynamic elements

http://jsfiddle.net/SergeyKozlov/tewyg2js/3/

我使用动态插入 HTML 代码使用按钮事件:

$("#NewItemImg").click(function(e) {
    e.preventDefault();
    itemCount++;

    var element = $("\
                    <div class=\"portlet ui-widget ui-widget-content ui-helper-clearfix ui-corner-all\">\
                        <div class=\"portlet-header ui-widget-header ui-corner-all\">img " + itemCount + "\
                            <span class='ui-icon ui-icon-closethick portlet-close'></span>\
                        </div>\
                        <div class=\"portlet-content\">\
                            <div class=\"form-group\">\
                                <input type=\"text\" class=\"form-control\" name=\"article[body][][img]\" id=\"ImageURL\" placeholder=\"Image URL\">\
                            </div>\
                            <button id=\"SetImageURL\" type=\"button\" class=\"btn btn-default\">Submit</button>\
                            <img id=\"PanelNewImageURL\" src=\"http://imgde.me/508f93cfb59b5.jpg\" alt=\"2014-12-10T18:04:41.762Z\" title=\"2014-12-10T18:04:41.762Z\" onerror=\"imgError(this);\">\
                        </div>\
                    </div>\
    ");

然后我尝试使用以下代码删除新的动态元素:

$("body").on('click', '.column  .portlet-close', function () {
    $(this).closest( ".portlet" ).remove();
});

在这种情况下它有效。问题是如何影响多个动态元素中的一个元素。

$("body").on('click', '.column #SetImageURL', function () {
    //e.preventDefault();
    // itemCount++;
    $("#PanelNewImageURL").show();
    $("#ImageURL").hide();
});

当我使用这段代码时,当你获取任何按钮时,只作用于第一个。

您看到此行为是因为 id 属性必须是唯一的,但您正在使用 "SetImageURL" 的多个实例作为 ID。当 jQuery 选择器在其中包含一个 id 引用时(如此处:on('click', '.column #SetImageURL' . . .),它仅作用于具有该 id 的第一个匹配元素,并忽略任何其他具有它的元素。

因此,您需要找到一种方法使其与纯 class 选择器一起使用,或者需要一种方法使 id 值唯一并将这些唯一的 id 值包含在选择器。我会选择第一种方法。 . .不过,无论哪种情况,您都应该真正使 id 值独一无二。 :)

编辑:

再次查看您的代码,试试这个:

$("body").on('click', '.column .btn-default', function () {
    //e.preventDefault();
    // itemCount++;
    $(this).siblings("img").show();
    $(this).parent().find(".form-control").hide();
});