jQuery / AJAX函数只执行一次

时间:2013-07-09 02:45:16

标签: jquery html ajax

我正在尝试使用jQuery和AJAX来提交和处理表单。表单用于喜欢/不同的按钮。当用户单击like /不同按钮时,表单将被提交(我在我的JSFIDDLE中注释掉了我的AJAX)然后表单被更改为相反的按钮文本。但是,由于某种原因,表单和按钮只会改变一次。我究竟做错了什么?我希望用户能够点击,然后不同,如果他们愿意的话再次喜欢。

我的代码:

$(".like-form").submit(function () {

    var dataString = $(this).serialize();
    var $this = $(this);

    //Ajax that submits the form to like.php

    $this.attr('class', 'unlike-form');
    $this.find('.like-button').html('Unlike');

    return false;

});

$(".unlike-form").submit(function () {

    var dataString = $(this).serialize();
    var $this = $(this);

    //Ajax that submits the form to unlike.php

    $this.attr('class', 'like-form');
    $this.find('.like-button').html('Like');

    return false;

});

3 个答案:

答案 0 :(得分:2)

您正在将提交事件绑定到不存在的表单,因为您正在更改现有表单的类。正确的方法是:

$("form").submit(function () {

    var $this = $(this);
    var isLiked = $this.hasClass('unlike-form');
    var dataString = $this.serialize();

    if ( isLiked ) {
        //Ajax that submits the form to unlike.php
    } else {
        //Ajax that submits the form to like.php
    }

    $this.toggleClass('like-form unlike-form');
    $this.find('.like-button').html(isLiked ? 'Like' : 'Unlike');

    return false;

});

我建议给表单一个特定的属性,以便您可以更直接地选择它。

答案 1 :(得分:1)

这是因为运行代码时没有'.unlike-form'

jQuery没有主动检查你的DOM是否有变化,并且在lopp或任何东西中重新运行代码。 您的代码是静态的,因此当它执行并尝试绑定事件时,它会找到.like-form并在其上绑定click事件。没有'.unlike-form'。

此外,你的代码正在改变元素的类,所以即使你有绑定代码工作,因为它仍然是相同的表单元素,它仍然具有原始的{{附加了1}}事件代码。

IMO,你的整个方法有点过时了。我建议更像这样的东西(未经测试):

.like-form

编辑:使我的推荐代码可重复使用。只需在任何元素上添加<button class="like-button is-unlike" data-like-button data-user-id="1" data-post-id="2">Like</button> <script> var $likeButtons = $('[data-like-button]'); $likeButtons.on('click', function() { var $likeButton = $(this); var isLiked = $likeButton.hasClass('is-liked'); var data = { mode: isLike ? 'like' : 'unlike' userId: $likeButton.data('user-id'), postId: $likeButton.data('post-id') } // do async request here if (isLiked) { $likeButton .removeClass('is-liked') .addClass('is-unliked') .text('Unlike'); } else { $likeButton .removeClass('is-unliked') .addClass('is-liked') .text('Like'); } return false; }); </script> 属性,然后在页面末尾运行一次脚本。

答案 2 :(得分:0)

您应该使用switchClass()。

switchClass(removeClassName, addClassName).

参考:http://api.jqueryui.com/switchClass/

并将提交更改为点击功能,一切都会正常工作..

相关问题