怎樣解決Js代碼中click事件重複觸發

最近在工作中遇到了一個bug,我在點擊"新建問題"時會彈出一個模態窗,在模態窗中,有一些勾選框可以進行選擇勾選,然後進行提交。當我信息沒有填寫完整時,關閉模態窗後,再次打開"新建問題"模態窗時,再去勾選選擇時,發現不能進行選擇。然後我開始去調試,發現這個click事件觸發了兩次,所以並沒有什麼變化。

接下來給大家看看相關代碼和截圖

$('.category').click(function () {
            //勾選框展示所屬領域
            check_cate = $(this).find('.checkbox').next().hasClass('hide');
            if (check_cate) {
                $(this).find('.checkbox').addClass('hide');
                $(this).find('.checkbox').next().removeClass('hide');
                $(this).find("label").find('input').prop('checked', true);
            } else {
                $(this).find('.checkbox').removeClass('hide');
                $(this).find('.checkbox').next().addClass('hide');
                $(this).find("label").find('input').prop('checked', false);
            }
        })

此時我們分析上面這段代碼這麼寫有什麼問題。  爲什麼事件會重複兩次執行?

然後查閱了一些資料以後發現,第二次的事件綁定和第一次的事件綁定都註冊到了同一個div身上,在jQuery中事件註冊同時註冊到同一個div時,只要不消毀就會累計執行。這就是根本原因所在。在這期間我嘗試過很多方法,結果都沒有成功。最終的解決方案如下:

// 防止click事件重複觸發,先解除綁定,再進行綁定
        $('.category').off('click');
        // 選擇所屬領域
        $('.category').click(function () {
            //勾選框展示所屬領域
            check_cate = $(this).find('.checkbox').next().hasClass('hide');
            if (check_cate) {
                $(this).find('.checkbox').addClass('hide');
                $(this).find('.checkbox').next().removeClass('hide');
                $(this).find("label").find('input').prop('checked', true);
            } else {
                $(this).find('.checkbox').removeClass('hide');
                $(this).find('.checkbox').next().addClass('hide');
                $(this).find("label").find('input').prop('checked', false);
            }
        })

沒錯,我們需要在綁定事件之前先解除再進行綁定,將jQuery事件進行銷燬再綁定。最後成功解決了這個bug。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章