2011-08-12 82 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 –