用于管理动态添加/删除textareas的NicEdit html编辑器 [英] NicEdit html editor for managing dynamic add/remove textareas
问题描述
您好我的动态添加textarea有问题,
Hi I am having problem with my dynamic add textarea,
我需要在我的所有textarea中都有niceEdit html编辑器,它在硬编码的textarea上运行良好但是当我使用我的javaScript动态添加函数来生成textarea它没有获得nicEdit html编辑器。
I need to have niceEdit html editor in all my textarea, It works good on hardcoded textarea but when I use my javaScript dynamic add function to to produce textarea it does not obtain the nicEdit html editor.
任何人都可以告诉我我在这里缺少什么。
任何评论和建议都很受欢迎。
could anyone tell me what I'm missing here. Any comments and suggestion is well appreciated.
这是我的 jsfiddle
推荐答案
一步一步走。您需要在每个新添加的控件上实例化新的nicEditor实例。
Take it step by step. You need to instantiate for the new nicEditor Instance on each newly added controls.
//Create the text area first and append it to DOM.
var elm = $('<TEXTAREA NAME="description[]" id="test" ></TEXTAREA><a href="#" id="remScnt">Remove</a>').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($('<p/>')); //You can chain it in the first step itself after appendTo(scntDiv).
Demo
$(document).on('click', '#addScnt', function () {
// Add the textarea to DOM
var elm = $('<textarea NAME="description[]"></textarea>').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($('<a/>', {
rel: curSize,
'class': "remScnt",
text: "Remove",
href: '#'
})).next().andSelf().wrapAll($('<p/>')); //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()
,包含动态创建元素的事件委派。同时将ID更改为类以删除链接 .remScnt
,因为重复ID可能导致问题并使html无效
Demo
Note live()
is deprecated and discontinued in newer version so use on()
with event delegation for dynamically created elements. Also change id to class for the remove link .remScnt
as duplicate id can cause issues and make the html invalid
这篇关于用于管理动态添加/删除textareas的NicEdit html编辑器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!