2011-08-12 80 views
1

我試圖從一個jQuery用戶界面對話框動態添加刪除按鈕,但似乎我的刪除功能將導致以下錯誤:jQuery的刪除按鈕

Uncaught TypeError: Cannot read property 'length' of undefined 
jquery-1.5.2.min.js:16 

,我真的不知道爲什麼,但如果我註釋掉我使用刪除按鈕功能一切正常。我上傳了一個基本的副本:http://jsfiddle.net/fS253/6/但對話框不會出現的jsfiddle

// Allows simple button addition to a ui dialog 
$.extend($.ui.dialog.prototype, { 
    'addbutton': function (buttonName, func) { 
     var buttons = this.element.dialog('option', 'buttons'); 
     buttons.push({text: buttonName, click: func}); 
     this.element.dialog('option', 'buttons', buttons); 
    } 
}); 

// Allows simple button removal from a ui dialog 
$.extend($.ui.dialog.prototype, { 
    'removebutton': function (buttonName) { 
     var buttons = this.element.dialog('option', 'buttons'); 

     for (var i in buttons) { 
      if(buttons[i].text==buttonName) { 
      delete buttons[i]; 
      } 
     } 

     this.element.dialog('option', 'buttons', buttons); 
    } 
}); 

actionsForm.dialog('addbutton', 'New Button', newButtonClickFunction); 
actionsForm.dialog('removebutton', 'New Button'); 

function newButtonClickFunction() { 
    alert('You clicked the new button!'); 
} 
+2

它不是的jsfiddle工作,因爲你沒有包括必要的jQuery UI的CSS文件。這是一個更新的版本http://jsfiddle.net/fS253/3/ – Lance

回答

3

的問題是,delete buttons[i];刪除元素,但依舊保持了數組長度相同的內工作。

簡單的解決辦法是創建一個新的陣列 - http://jsfiddle.net/m3a7a/

+1

我總是忘記簡單的事情......謝謝!使用''if(i!= - 1)buttons.splice(i,1);''now –