2014-01-25 162 views
1

新手在這裏..防止js函數運行多次

我有一個運行,由​​於3次,我有調用函數3次js函數..

var deleteFunc = function() { 
    $('.delete').on('click', function(){ 
     // ajax code here... 
    }); 
}; 

(loadData = function(){ 
    // this will be in a loop didn't place its because it too long 
    var content = '<tr><td>1</td><td>John</td><td><span class="delete">Delete</span></td></tr>'; 

    $('#first_tbl').append(content); 

    deleteFunc(); 
})(); 

(loadSecondData = function(){ 
    // this will be in a loop didn't place its because it too long 
    var content = '<tr><td>1</td><td>John</td><td><span class="delete">Delete</span></td></tr>'; 

    $('#second_tbl').append(content); 

    deleteFunc(); 
})(); 

(loadThirdData = function(){ 
    // this will be in a loop didn't place its because it too long 
    var content = '<tr><td>1</td><td>John</td><td><span class="delete">Delete</span></td></tr>'; 

    $('#third_tbl').append(content); 

    deleteFunc(); 
})(); 

當我點擊.deletedeleteFunc()將運行3次。

我有一個想法,我將創建3刪除功能,如deleteFunc()deleteSecondFunc()deleteThirdFunc(),但我注意到它將是多餘的,因爲它具有相同的功能和代碼。

任何人都可以幫助我如何解決這個問題嗎?

+0

*爲什麼*你爲什麼要調用'deleteFunc'三次? –

+3

所以......你調用一個函數3次,但你不想讓它運行3次? –

+0

@FelixKling,因爲如果用戶對數據進行了更改,有時'loadData'或'loadSecondData'或'loadThirdData'將再次運行。 – justin

回答

2

刪除先前的綁定,然後添加新的綁定。

var deleteFunc = function() { 
    $('.delete').off('click').on('click', function(){ 
     // some ajax code here... 
    }); 
};