【问题标题】:NicEdit html editor for managing dynamic add/remove textareas用于管理动态添加/删除文本区域的 NicEdit html 编辑器
【发布时间】:2013-06-29 07:08:41
【问题描述】:

您好,我的动态添加文本区域有问题,

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

谁能告诉我我在这里缺少什么。 非常感谢任何 cmets 和建议。

这是我的jsfiddle

【问题讨论】:

    标签: php javascript jquery css nicedit


    【解决方案1】:

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

    //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(); 
    
     });
    

    Demo

    注意 live() 在较新的版本中已弃用并停止使用,因此请使用 on() 与事件委托来动态创建元素。还要将删除链接的 id 更改为 class .remScnt,因为重复的 id 可能会导致问题并使 html 无效

    【讨论】:

    • 看起来不错,还有一件事。 remove 链接无效,但是谢谢谢谢!
    • @kodewrecker 让我看看删除。
    • @kodewrecker 给你。让我用解释更新答案。 jsfiddle.net/HwF8g
    • 我也在为 remove 做并行编码,但是你已经做到了......完美。谢谢,谢谢!你真善良。
    猜你喜欢
    • 2021-05-20
    • 1970-01-01
    • 2022-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多