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

Javascript 当一个函数完成时调用jquery函数,javascript,jquery,html,ajax,Javascript,Jquery,Html,Ajax,因此,我有一个jqueryclick函数分配给开/关切换。非常简单的脚本: $('.on-off').on('click', function(e) { e.preventDefault(); var $this = $(this); $this.find('.slider').toggleClass('active'); }); 我们有两个版本的切换。单击时立即切换,然后单击nextaka submit时提交值 我们的另一个调用jqueryajax函数,如果它是在后端

因此,我有一个jqueryclick函数分配给开/关切换。非常简单的脚本:

$('.on-off').on('click', function(e) {
    e.preventDefault();
    var $this = $(this);
    $this.find('.slider').toggleClass('active');
});
我们有两个版本的切换。单击时立即切换,然后单击nextaka submit时提交值

我们的另一个调用jqueryajax函数,如果它是在后端定义的特定消息代码,则在成功和成功之间切换

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);
                }
            });
     }
正如您所看到的,我必须使用相同的代码再次切换该类,但要使用直接目标

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

我的目标是让我的第一组代码以元素为目标并切换类来完成所有这一切,但动态地切换到不必每次调用函数的位置

从概念上讲,我认为:

$('.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更改

这里有一个链接,指向基本的开/关切换


我希望我解释的足够详细。

您应该测试$this.attr'onclick'='function'的类型。如果clickfunction=true是一个赋值,则返回true并始终通过测试。感谢您的回复。如何准确地提取函数名,并从html中编写的基本onclick函数中分别调用它。因此,如果在a href或what ever元素中,它有一个onclick=myFunction。我如何防止它触发,而是使用jquery on click处理程序进行开/关切换,并在其中调用html onclick处理程序?这还不清楚,因为我必须考虑它的时间跨度。听起来太复杂了。您不需要提取函数,因为您可以在JS或jQuery中使用它来调用定义的onclick处理程序。