2017-05-07 49 views
-1

我有以下代碼在jquery中。Javascript綁定和取消綁定函數調用

$(document).ready(function() { 
    console.log('Hello'); 

    var uploadButton = $('#upload-button'); 

    uploadButton.on('click', function() { 
     uploadButton.unbind('click'); 
     progressBar(); 
     uploadButton.bind('click'); 
    }); 

}); 

function progressBar(){ 

    var element = document.getElementById('bar'); 
    var width = 1; 
    var id = setInterval(addFrame, 25); 

    function addFrame() { 
     if(width == 100){ 
      clearInterval(id); 

      element.style.width = 0; 
      return true; 
     } 

     width += 1; 
     element.style.width = width + '%'; 
    } 

} 

我想要做的就是按下一個HTML button項目時被調用函數的進步蝙蝠,也嘗試禁用了電話,除非當前通話結束。最初的想法是在按下時解除綁定click事件,執行該功能,然後再將click綁定到同一元素,但到目前爲止,我所得到的唯一一件事情只有一個呼叫progressBar,之後,button對於click仍然沒有約束。
我在做什麼錯?
謝謝。

+0

在這裏尋找關於如何刪除點擊甚至是暫時:http://stackoverflow.com/questions/1921855/jquery-how-can-i-temporarily-disable-the-onclick-event-listener-after-the-even – Benedikt

回答

0

您的代碼的問題是解除綁定方法,此方法不會將事件置於開/關中,否則會刪除與按鈕關聯的功能,解除綁定不是解決該問題的方法。 對於暫時移除了點擊事件,我建議這樣做:

  • 使用$('#myButton').prop('disabled', true)

  • 禁用HTML按鈕並啓用,在進度條功能的一個回調函數後使用$('#myButton').prop('disabled', false)

我希望這可以幫助你

0

我自己找到了答案,使用prop

$(document).ready(function() { 
    console.log('Hello'); 

    var uploadButton = $('#upload-button'); 

    uploadButton.on('click', function() { 
     console.log('clicked'); 
     progressBar(uploadButton); 
    }); 

}); 

function progressBar(target){ 

    target.prop('disabled', true); 

    var element = document.getElementById('bar'); 
    var width = 1; 
    var id = setInterval(addFrame, 25); 

    function addFrame() { 
     if(width == 99){ 
      clearInterval(id); 
      element.style.width = 0 + '%'; 

      target.prop('disabled', false); 
     } 

     //make it to display actual file upload 

     width += 1; 
     element.style.width = width + '%'; 
    } 
} 

傳遞對象作爲參數,我設法禁用它,進行操作,然後啓用它。也可能與其他屬性一起工作。