绑定动态添加的表单以使用jQuery提交事件 [英] Bind dynamically added form to submit event with jQuery

查看:208
本文介绍了绑定动态添加的表单以使用jQuery提交事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您在jQuery中使用相同的表单ID动态创建多个表单时,处理提交事件的最佳方法是什么?

What would be the best way to handle the submit event when you have multiple forms dynamically created with the same form id in jQuery?

到目前为止,此行使jQuery仅处理第一种形式.

So far this line makes that jQuery only handles the first form.

$("form#noteform").submit(function(){
  // do stuff
});

有点混乱,因为我确实需要捕获特定表单的提交才能获得正确的帖子值,因此表单的选择器必须唯一.

Kind of confusing, because I really need to catch the submit of a particular form to get the correct post values, therefore the selector of the form must be unique.

您如何让它侦听所有提交内容,以后再确定启动提交内容的表单ID是否正确?

How can you make it listen to all submits and later identify if it is the correct form id that launched the submit?

推荐答案

没有最佳方法使用ID,因为具有多个具有相同ID的元素是无效的HTML.

There is no best way to do this using ID's, because having multiple elements with the same ID is invalid HTML.

我建议您的表单具有唯一的ID,但共享一个类名.如果随后需要获取第一个,则可以直接使用ID或类以及jquery:first选择器.

I would suggest instead your forms have unique ID's but share a class name. If you then needed to get the first one, you could use the ID directly or the class and the jquery :first selector.

$('form.className:first').submit(function(){
  stuff();
});

-edit-试图实际解决识别已提交哪种表格的问题.同样,此解决方案依赖于唯一表单ID

-edit- Trying to actually address the issue of identifying which form has been submitted. Again this solution relies on Unique form ID's

$('form.className').submit(function(){
  switch( $(this).attr('id') ){
    case 'form1id':
      submitForm1();
      break;
    case 'form2id':
      submitForm2();
      break;
    default:
      stuff()
      break;
  }      
});

这篇关于绑定动态添加的表单以使用jQuery提交事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆