【问题标题】:jquery closest('form') doesn't serializejquery最接近('form')不序列化
【发布时间】:2012-11-24 14:02:49
【问题描述】:

我用它作为评论的形式。页面上有很多这个类,所以我必须选择最接近的形式,但它不起作用。

$(document).ready(function() {
$(".comment_but").on('click',function(){
    var location2 = $(this).closest('div');
    var datastring = $(this).closest('form').serialize();
        $.ajax({
        type: "POST",
        url: "comment_save.php",
        data:  datastring,
        cache   : false,
        success: function(html){
$('.comment_show',location2).html(html);}});});});

还有我的 HTML

<div class="comment_show"></div>
<tr>
        <form onSubmit="return false;" name="comment_form" id="comment_form" style=" display:inline; ">
            <td align="right"><textarea name="comment_box" cols="70" rows="2"></textarea></td>
                        <td>
            <input name="post_id" type="hidden" value="<? echo($data['post_id']); ?>" />
            <input name="Send" class="comment_but" value="Comment!" type="submit" /></td>
        </form>
</tr>

【问题讨论】:

  • 为我工作 - jsfiddle.net/Bv6QJ
  • 谢谢,我会再次检查我的代码。 :S
  • 也许 onSubmit 属性会阻止您的代码运行。您可以尝试将return false 移动到jQuery 事件监听器吗?
  • 结果不变。但是谢谢!

标签: jquery html ajax forms closest


【解决方案1】:

将代码放在onsubmit中

$(document).ready(function() {
  $("#comment_form").on("submit",function(){
    var datastring=$(this).serialize();
    $.ajax({
      type: "POST",
      url: "comment_save.php",
      data:  datastring,
      cache   : false,
      success: function(html){
        $('.comment_show',location2).html(html);
      }
    });
    return false; // mandatory
  });
});

【讨论】:

  • 在这种情况下,返回 false 不是强制性的,因为 OP 已经有 onSubmit="return false"。但是等等:这可能会阻止 OP 的代码运行吗?
  • mplungjan,最后!!,我使用您的代码并将 id="comment_form" 更改为 class="comment_id" 以便它适用于每个元素。太感谢了!!!! @11684 我在这两个地方都有“return false”,而且效果很好
  • 好吧,只是随机猜测! @Expl0de
  • 我的建议完全替代了return false
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-29
  • 2010-11-17
  • 1970-01-01
  • 1970-01-01
  • 2015-07-26
  • 1970-01-01
相关资源
最近更新 更多