当一个函数完成时调用jquery函数

时间:2014-06-16 14:56:08

标签: javascript jquery html ajax

所以我有一个分配给开/关切换的jquery点击功能。非常简单的脚本:

$('.on-off').on('click', function(e) {
    e.preventDefault();
    var $this = $(this);
    $this.find('.slider').toggleClass('active');
});

我们有两个版本的此切换。单击后立即切换,然后在单击下一步(即提交)时提交值。

我们的另一个调用jquery ajax函数,该函数在成功时切换,如果它是在后端定义的特定消息代码,则成功。

jQuery.ajax({
                url: url,
                type: 'POST',
                dataType: 'json',
                cache: false,
                data: {'requestType': requestType},
                success: function(message) {
                    if(message.STATUS=='2000'){
                        if(currentButtonClicked=='dashboardChargingButton'){
                            if($('#dashboardChargingButton').html()==startCharge)
                                $('#dashboardChargingButton').html(stopCharge);
                            else
                                $('#dashboardChargingButton').html(startCharge);
                         }
                        if(currentButtonClicked=='invokeChargingButton'){
                            $( "#invokeChargingButton .slider" ).toggleClass( 'active');
                        }
                    }
                },
                error: function(xhr, ajaxOptions, thrownError) {
                    alert(xhr.status + " - " + xhr.statusText);
                }
            });
     }

正如您所看到的,我必须使用相同的代码再次切换课程,但需要直接定位。

这种类型的开关切换在实际的html中有一个onclick,调用处理这个ajax的函数。

我的目标是让我的第一组代码成为以元素为目标的代码,并切换类来完成所有这些操作,但动态地转到我们不必每次都调用函数的地方。

从概念上讲,我的想法是:

$('.on-off').on('click', function(e) {
    e.preventDefault();
    var $this = $(this);
    if (!$this.attr('onclick')) {
        $this.find('.slider').toggleClass('active');
    } else {
        var clickFunction = $this.attr('onclick');
        call the clickFunction
        if (clickfunction = true) {
            $this.find('.slider').toggleClass('active');
        }
    }
});

这样做会抓住onclick,但在我指定之前不要调用它。在ajax请求中,而不是切换,我只会返回true。

这可能不是最好的方法。我只是试图对所有内容进行封装以限制代码量,并在任何潜在缺陷的情况下对这些元素进行所有dom更改。

这是一个指向开/关切换的基本小提琴的链接。

Fiddle

我希望我能够详细解释所有内容。

0 个答案:

没有答案
相关问题