如何将Div的id作为参数传递给函数

How to pass the id of Div as an argument to a function

本文关键字:参数传递 函数 id Div      更新时间:2023-09-26

我有一个div,只需使用jQuery单击按钮即可动态添加到页面中。

我希望能够使用RemoveArtist()功能点击交叉按钮.png来删除Div。

$("<div class='"input-append'" id='"artist"
    + artists.length - 1 + "'" ><label style='"background-color:#e0ffff'">"
    + artistVal + "</label><img onclick='"RemoveArtist()'" id='"removeartist'""
    + " src='"/Content/bootstrap/img/cross-button.png'" /></div>")
    .appendTo(addDiv);

移除艺术家功能应该如下所示:

var RemoveArtist = function (div,artistlength) {
    $('div').remove();
    artists.splice(artistlength, 1);
};

如何将实际的div传递给RemoveArtist函数,以及作为div的artists.length - 1值的artistlength

所以基本上,我试图删除Div,并从艺术家数组中删除艺术家。

在我看来,最好创建实际元素而不是字符串
这是更多的东西要写,但使每一件事都更容易跟踪:

var input_append = $('<div />', {id: 'artist' + (artists.length - 1)}),
    label        = $('<label />', {style: 'background-color:#e0ffff',
                                   text : artistVal
                                  }
                    ),
    image        = $('<img />', {id:  'removeartist',
                                 src: '/Content/bootstrap/img/cross-button.png',
                                 on: {
                                       click: function() {
                                          input_append.remove();
                                          artists.splice(artists.length - 1, 1);
                                       }
                                     }
                                }
                    );
addDiv.append( input_append.append(label, img) );