我有一个表单,当用户点击标签时,我使用JavaScript提交它。但是有一种奇怪的行为,即数据没有被提交。但是,如果我延迟提交表单(即使是0秒的延迟),它就可以正常工作。
以下是HTML代码:
<form action="/other-page" method="post">
<input id="val-1" type="checkbox" name="filter[]" value="1">
<label for="val-1">Value 1</label>
<input id="val-2" type="checkbox" name="filter[]" value="2">
<label for="val-2">Value 2</label>
</form>
脚本:
该脚本:
<script>
$('label').click(function() {
var form = $(this).closest('form')
// if I use the following line the values won't be set
form.submit()
// If I use a `setTimeout` it works, even with a delay of 0
setTimeout(function() {
form.submit()
}, 0)
})
</script>
这并不是一个大问题,因为我可以使用 setTimeout
解决,但在延迟为 0 的情况下编写这样的代码真的很丑陋。我认为可能是浏览器bug,但我已在Chrome和Firefox上进行了测试,结果相同。
你有什么想法吗?
click
事件在值实际被更改之前被触发。 - Felix Klingform[0].submit()
。 - Ram