【发布时间】:2016-11-28 11:27:39
【问题描述】:
我可以将 add 值输入到输入和 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')
});
我试图不走反应路线,因为我想在副项目中使用纯 jquery。
我想要的只是<input id="selective-avatars" name="avatars[]" type=hidden value="1,2, etc" /> 去控制器。
【问题讨论】:
-
@Satpal 那会给我
undefined。我所拥有的可以很好地找到 ID。 -
@Sylar:OP 的版本是完全有效且适当的 ES2015 解构赋值。
-
@T.J.Crowder 是的,刚刚意识到 ;)
-
旁注:问题中有一个错误重复了三遍(我刚刚修复了它),
id上缺少":<input id="selective-avatars name="avatars[]" type=hidden value="1,2" />如果那是复制和-从您的代码粘贴,您可能需要仔细检查实际代码以查看它是否丢失。
标签: javascript jquery arrays ruby-on-rails-5