选择正确的元素以从函数内触发表单提交

Selecting the correct element to trigger form submit from within a function

我在一个页面上有多个表单。这些表格实际上是 PayPal "add to cart" 按钮。当用户点击一个按钮时,一个警告框会询问他们的邮政编码。如果 okZips 数组中的邮政编码,我想通过提交按钮以编程方式跟随 link 到购物车,但我无法完全获得将 .submit() 附加到的正确元素。

$(this).add("div.check-zip").add("form:first").submit();//this submits the first form on the page
$(this).add("div.check-zip").add("form").submit();//this submits the last form on the page
$(event.target).add("form").submit();//this doesn't submit anything
$(myEvent).add("form").submit();//this submits the last form where myEvent is a global variable

这支笔可以在这里找到: http://codepen.io/enielsen0001/pen/KwEbzz

如何 select 应用 .submit() 的正确元素?我是不是搞错了?

你并没有走错路,但这绝对是最糟糕和最肮脏的方式。好像你不知道自己在做什么。你的 类 搞砸了,你在混合 jQuery 和纯 js,你在使用 while 和 for。似乎您故意复制粘贴的代码而不知道它是什么。在发布问题之前,请至少具备初学者 js/jQuery 的知识。

但是,这里是更新的笔http://codepen.io/anon/pen/NPJJwJ

您需要实际的表单对象才能提交。

// myEvent is event itself not element
$(myEvent.target).parent("form").submit();

我已经重构了涉及您使用的 while 和 for 循环的内容。将您的代码与更新后的代码进行比较。希望对您有所帮助: