.closest('form').find(':checkbox') 解释逻辑
我有两种表格,表格1和表格2;两种形式都位于同一文档或页面中。这些表格通过复选框来区分;表单 1 有一个复选框输入元素,而表单 2 中没有复选框元素。
目前,我正在尝试使用以下代码测试复选框输入元素是否存在:
if(jQuery(this).closest("form").find(':checkbox')){...}
当我单击表单 2 提交时,找到复选框。
截至目前,我了解到 .closest 会将上下文设置为找到的最接近的表单元素。如果我触发没有复选框的表单 2,为什么它会找到表单 1 的复选框?
显然我误解了这是如何工作的。有人可以解释一下吗?
I have two forms, form 1 and form 2; both forms are located in same document or page. These forms are differentiated by a checkbox; form 1 has a checkbox input element, and form 2 has not checkbox element within.
Currently, i am trying to test for the existence of the checkbox input element with the following code:
if(jQuery(this).closest("form").find(':checkbox')){...}
when I click form 2 submit, checkbox is found.
As of now, I understand that .closest will set the context to the closest form element found. And If am triggering form 2, which has no checkbox, why is it finding the checkbox of form 1?
Obviously I have misunderstood how this works. Could somebody explain?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为你的问题的原因是所有 jQuery 选择都是真实的。即使是空的 jQuery 选择也会传递
if
条件:您必须检查
length
属性来查看是否找到任何元素:如果没有找到元素,则
length
将为0
,这是一个 false-y值,因此条件将失败。如果找到任何元素,length
将大于0
,因此条件将通过。I think the reason for your problem is that all jQuery selections are truthy. Even an empty jQuery selection will pass an
if
condition:You have to check the
length
property to see if any elements are found:If there are no elements found, the
length
will be0
, which is a false-y value, so the conditional will fail. If any elements are found, thelength
will be greater than0
, so the conditional will pass.