用于管理动态添加/删除textareas的NicEdit html编辑器

嗨,我的动态添加textarea有问题,

我需要在我的所有textarea中都有niceEdit html编辑器,它在硬编码的textarea上运行良好,但是当我使用我的javaScript动态添加函数来生成textarea时,它不会获得nicEdit html编辑器。

有谁能告诉我我在这里失踪了什么。 任何意见和建议都非常感谢。

这是我的jsfiddle

一步一步走。 您需要在每个新添加的控件上实例化新的nicEditor实例。

 //Create the text area first and append it to DOM. var elm = $('Remove').appendTo(scntDiv); // Instantiate the nicEditor Instance on it. It will now have the reference of the element in DOM. new nicEditor().panelInstance(elm[0]); //wrap it with p elm.wrap($('

')); //You can chain it in the first step itself after appendTo(scntDiv).

演示

添加/删除function的完整更新:

  $(document).on('click', '#addScnt', function () { // Add the textarea to DOM var elm = $('').appendTo(scntDiv); //Get the current SIZE of textArea var curSize = $('textarea[name="description[]"]').length; //Set the Object with the index as key and reference for removel editors[curSize] = new nicEditor().panelInstance(elm[0]); //Create anchor Tag with rel attribute as that of the index of corresponding editor elm.after($('', { rel: curSize, 'class': "remScnt", text: "Remove", href: '#' })).next().andSelf().wrapAll($('

')); //add it to DOM and wrap this and the textarea in p }); $(document).on('click', '.remScnt', function (e) { e.preventDefault(); //Get the textarea of the respective anchor var elem = $(this).prev('textarea'); //get the key from rel attribute of the anchor var index = this.rel; //Use it to get the instace and remove editors[index].removeInstance(elem[0]); //delete the property from object delete editors[index]; //remove the element. $(this).closest('p').remove(); });

演示

注意不推荐使用live()并在较新版本中停止使用on()因此on()事件委托使用on()来动态创建元素。 同时将id更改为类以删除链接.remScnt作为重复ID可能导致问题并使html无效