我动态地向表单添加隐藏的输入。如果您的消息是同时说四个人(其名称在callsign_array
中),则会添加四个隐藏的输入。然后使用ajax提交表单。然后我想要删除所有附加的隐藏输入,但是$('.remove').remove();
不起作用(如果您向Andy发送消息,然后尝试向Barry发送不同的消息,它实际上将消息发送给Andy和Barry。向Chas发送第三条消息将向Andy,Barry和Chas发送消息。我知道有成千上万的类似“jquery remove()无法正常工作”的问题,我看过它们,我觉得这应该有用,但我很困惑,我只是看不出有什么不对。< / p>
var callsign_array = $('#callsigns-div').data('callsigns');
var form = $("#message_form");
for(var i=0; i<callsign_array.length; i++) {
form.append('<input type="hidden" class="remove" name="callsigns[]" value="' + callsign_array[i] + '" />');
}
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'script'
});
// remove all appended inputs
$('.remove').remove();
// reset the callsigns array
$('#callsigns-div').attr('data-callsigns', '[]');
该页面包含此div来保存callsigns数组:
<div id="callsigns-div" data-callsigns='[]'></div>
答案 0 :(得分:1)
<crystalball on>
您没有从callsign_array
容器中删除条目。这就是不同用户的消息累积的原因。
</crystalball off>
添加日志记录:
console.log("Before remove: ", $('.remove').length);
$('.remove').remove();
console.log("After remove: ", $('.remove').length);
让自己相信$().remove
有效。
更新
在读取/写入DOM元素的数据集属性时,不要混用$().data
和$().attr
调用。这些数据集项由jQuery缓存为单独的内存对象。
添加日志记录:
$('#callsigns-div').attr('data-callsigns', '[]');
console.log("Hope array is empty: ", $('#callsigns-div').data('callsigns'));
说服自己,$().attr
电话对后续$().data
电话的结果不起作用。
答案 1 :(得分:0)
@ robert-wade是对的。我没有代表注释,但您可能会考虑将所有用户保存在数组或对象中,然后在表单中传递该数组/对象。它比添加/删除元素更清洁。当然你必须在服务器端解析它。
答案 2 :(得分:-1)
试试这个
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'script' ,
success: function (){
$('.remove').remove(); // reset the callsigns array
$('#callsigns-div').attr('data-callsigns', '[]');
}
}); // remove all appended inputs