3

我之前的问题之后, Meder很快就回答了这个问题,这并不好笑,现在在提交可重用 jQuery 表单的过程中弹出了一个额外的问题,它不会让用户离开他们所在的位置.

问题

jQueryserialize()函数在页面内的所有表单上执行它的魔力,而不是在提交的特定表单上。下面的示例代码。

如何捕获表单的唯一名称/ID,并"form"在其中替换$("form").serialize()为目标表单的名称,以便仅对其进行序列化?

表格代码

<form name="contact" id="contact" action="">
  <input name="_recipients" type="hidden" value="joe@fake.com" />
  <input name="_subject" type="hidden" value="Title" />
  ...
    <fieldset>
      <label for="name" id="name_label">Name</label>
      <input type="text" name="name" id="name" size="30" value="" class="text-input" />
      <label class="error" for="name" id="name_error">This field is required.</label><br />

      <label for="email" id="email_label">Return Email</label>
      <input type="text" name="email" id="email" size="30" value="" class="text-input" />
      <label class="error" for="email" id="email_error">This field is required.</label><br />

      <label for="phone" id="phone_label">Return Phone</label>
      <input type="text" name="phone" id="phone" size="30" value="" class="text-input" />
      <label class="error" for="phone" id="phone_error">This field is required.</label><br/>

        <br />
      <input type="submit" name="submit" class="button" id="submit_btn" value="Send your suggestion" />
    </fieldset>
  </form>

jQuery 序列化和发布

    var dataString = $("form").serialize();
    //alert (dataString);return false;

    $.ajax({
      type: "POST",
      url: "/_global/assets/scripts/formmail/formmail.asp",
      data: dataString,
...
4

3 回答 3

4
var dataString = $('#contact').serialize()

如果您将事件处理程序附加到按钮或表单的事件,那么您可以在事件处理程序函数范围内使用 ifsubmit引用它,例如thissubmit

$('#contact').submit(function() {
 alert( $(this).serialize() );
});

我强烈推荐阅读http://docs.jquery.com/Selectors

于 2009-10-20T06:30:13.653 回答
2

通过使用“form”字符串作为选择器,您实际上得到FORM了页面内的所有元素,为了只选择一个表单,您可以:

通过 id 属性获取特定表单(使用id 选择器):

var dataString = $("#contact").serialize();

或者通过它的 name 属性(使用attributeEquals选择器):

var dataString = $("form[name=contact]").serialize();
于 2009-10-20T06:31:20.827 回答
0
$("#contact").serialize()

而不是使用serialize有一个很好的插件,它允许您异步发布您的表单。你所要做的就是:

$(function() {)
    $('#contact').ajaxForm(); 
});

另外不要忘记为表单分配正确的操作,它不应该为空。

于 2009-10-20T06:30:49.750 回答