AJAX Call - Flickering more for each click

时间:2018-12-19 11:37:58

标签: javascript jquery ajax

I'm building a chart (in Yii2 Framework) that can show different report for each period, i need to update the chart if the user click on the button group with 7D-1M-1Y.

The update work, but every time i change the view period with button click, the flicker times before the right chart is shown, becomes higher.

This is my JS:

if(!$('#7D').hasClass('active') && !$('#1M').hasClass('active') && !$('#1Y').hasClass('active')) { $('#1M').addClass('active'); }
$('#7D').click(function() {
    var myValue = "7D";
    $.get("",{val:myValue},function(data){
        $('.btn').removeClass('active');
        $('#7D').addClass('active');
        $('#w2').fadeOut('fast', function(){
            $('#w2').html(data).fadeIn('fast');
        });
    });
});
$('#1M').click(function() {
    var myValue = "1M";
    $.get("",{val:myValue},function(data){
        $('.btn').removeClass('active');
        $('#1M').addClass('active');
        $('#w2').fadeOut('fast', function(){
            $('#w2').html(data).fadeIn('fast');
        });
    });
});
$('#1Y').click(function() {
    var myValue = "1Y";
    $.get("",{val:myValue},function(data){
        $('.btn').removeClass('active');
        $('#1Y').addClass('active');
        $('#w2').fadeOut('fast', function(){
            $('#w2').html(data).fadeIn('fast');
        });
    });
});

This is my Button Group:

<?= ButtonGroup::widget([
    'buttons' => [
        ['label' => '7D', 'id' => '7D'],
        ['label' => '1M', 'id' => '1M'],
        ['label' => '1Y', 'id' => '1Y'],
    ],
]); ?>

TIP: I tried with body instead of #w2 (the id of the chart), and it works properly without increments the flickering time, but flicker one time vertically, when the chart diseppear the page go to the top and then return to the new bottom.

Solve this can also be helpful, i only need a solution, is not important how

1 个答案:

答案 0 :(得分:5)

根据您的问题,我认为您的点击事件已多次附加到您的元素中。为避免多次连接,可以使用

$("#SomeId").off("click").on("click", function({
    // Your logic here.
})); 

尽管问题尚不清楚。