代码之家  ›  专栏  ›  技术社区  ›  Alexis Perrier

通过Ajax调用加载部分时未加载yu编辑器

  •  0
  • Alexis Perrier  · 技术社区  · 14 年前

    在Rails应用程序中,我通过Ajax调用加载了一个部分。(仍在使用原型)

    部分表单包含一个用Yahoo Yui_编辑器丰富的文本区域(类似于Tinymce或Fckeditor)

    <%= f.text_area :body, :class => 'rich_text_editor',  :rows => "15", :style => "width : 90%;"  %>
    

    当通过Ajax调用加载表单时,未加载yu编辑器,文本区域内容显示为简单文本。

    我测试了当直接加载相同的部分而不使用任何Ajax调用时,yui_编辑器是活动的。

    我知道这与未加载yui_编辑器javascript有关,但我不知道如何解决这个问题。

    非常感谢你的帮助

    谢谢

    1 回复  |  直到 14 年前
        1
  •  1
  •   Community CDub    8 年前

    你需要启动yui编辑器。因为编辑器需要元素的ID,所以需要在部分中指定唯一的ID。

    YUI doc 有关编辑器参数的详细信息

    补充

    您是通过Ajax添加DIV吗?在这种情况下,您需要在添加DIV之后调用YUI编辑器库。有两种方法可以做到这一点:

    1)您的代码需要显式地调用yui编辑器,它将插入到dom中(使用Ajax调用的结果)。例如,Ajax结果可以包括文本区域的元素ID,您可以提前知道它,等等。

    2)您可以在Ajax结果中包含调用yui编辑器的脚本。但是,在将脚本添加到DOM之后,您需要运行HTML中的脚本。

    设置元素的innerhtml属性不会运行HTML中的任何脚本。但我有一个脚本,可以,见下面。

    脚本基于此 SO Question

    ... do ajax call and get results in <body>
    foo_el.innerHTML = body; // add results to the dom
    
    exec_body_scripts(foo_el); // run any scripts in foo_el
    
    //////////////////////////////////
    
    function exec_body_scripts(body_el) {
      // Finds and executes scripts in the dialog's body.
      // Needed since innerHTML does not run scripts.
      // NB: Only looks for scripts that are children or grandchildren of body_el.
      // Doesn't look deeper.  
    
      function evalScript(elem) {
        var data = (elem.text || elem.textContent || elem.innerHTML || "" ),
            head = document.getElementsByTagName("head")[0] ||
                   document.documentElement,
            script = document.createElement("script");
    
        script.type = "text/javascript";
        try {
          script.appendChild(document.createTextNode(data)); // doesn't work on ie
        } catch(e) {
          // IE has funky script nodes
          script.text = data;
        }
    
        head.insertBefore(script, head.firstChild);
        head.removeChild(script);
      };
    
      // main section of function
      var scripts = body_el.getElementsByTagName('SCRIPT'), i;
    
      for (i = 0; scripts[i]; i++) {
        evalScript(scripts[i]);
      }
    };    
    

    部分示例:

    <% el_id = "rte_#{foo.id}"
    # foo is the name of an object used by the partial. Using its id
    # to ensure a unique id for the element on the page.
    # Or use a simple counter "i". But in any case, the el_id must be unique
    %>
    <%= f.text_area :body, :class => 'rich_text_editor',  :rows => "15", 
        :style => "width : 90%;", :id => el_id  %>
    
    <script>
      (function() {
        var myEditor = new YAHOO.widget.Editor('<%= el_id %>', {
          height: '300px',
          width: '522px',
          dompath: true, //Turns on the bar at the bottom
          animate: true //Animates the opening, closing and moving of Editor windows
          });
        myEditor.render();
      })();    
    </script>