Add/Remove 以逗号分隔的输入值 jquery

Add/Remove comma-separated input values with jquery

我可以 add values to an input and remove 但我想要实现的目标看起来很乱。

我有两张图片,点击后会显示它们的用户 ID。因此,当单击时,会添加一个隐藏的输入值 1。当点击另一个图像时,相同:

<input id="selective-avatars" name="avatars[]" type=hidden value="1,2" />

如果同一张图片被点击,它们的 id 将再次被删除(就像 toggleClass 之类的东西)。这是我将两个链接拼凑在一起时遇到的棘手部分。

完整 HTML(示例):

<img src="url" id="1" class="avatar" />
<img src="url" id="2" class="avatar" />
# Should this be in the loop also? It's currently not.
<input id="selective-avatars" name="avatars[]" type=hidden />

JS:

$('.avatar').click(function(){
  let {id} = this;
  //let array = $('#selective-avatars').val().split(',');
  $('#selective-avatars').val(function(i, val){
     return [val + (!val ? '' : ',') + id];
  });
  //Removed about 8 lines as nothing works

  //$(this).toggleClass('avatar-circle-display-loop-select')
});

我试图不走 React 路线,因为我想在副项目中使用纯 jquery。

我只想<input id="selective-avatars" name="avatars[]" type=hidden value="1,2, etc" />去控制器。

看起来 .avatar 元素上的 id 告诉我们要在隐藏输入中包含哪些值。我会在元素上保留一个标志,每次都重建输入值:

$('.avatar').click(function(){
    var $this = $(this);
    $this.data("selected", !$this.data("selected")); // Will be `undefined`
                                                     // initially, which is falsy
    var value = $('.avatar')
        .filter(function() {
            return $(this).data("selected");
        })
        .map(function() {
            return this.id;
        })
        .get()
        .join(",");
    $("#selected-avatars").val(value);
});

我注意到你已经使用了 ES2015 及更高版本的功能,所以在 ES2015 中:

$('.avatar').click(function() {
    const $this = $(this);
    $this.data("selected", !$this.data("selected")); // Will be `undefined`
                                                     // initially, which is falsy
    const value = Array.from($('.avatar'))
        .filter(elm => $(elm).data("selected"))
        .map(elm => elm.id)
        .join(",");
    $("#selected-avatars").val(value);
});