从下拉列表中向wysiwyg插入文本

时间:2013-09-05 12:10:12

标签: jquery html5 twitter-bootstrap wysiwyg

有没有办法如何使用jquery插入文本到bootstrap wysiwyg? 顺便说一下,我在这个页面使用了bootstrap-wysihtml5 http://jhollingworth.github.io/bootstrap-wysihtml5/ 文本实际上是来自下拉列表的模板,然后应该在wysisyg上插入onchange值。

我试过这段代码,但它只在隐藏的textarea上插入文本而不是在wysiwyg上

$(document).ready(function(e) {
    $("#template").change(function(){
        var template = $("#template").val();
        if(template != '') {
            $('.textarea, .wysihtml5-sandbox').append(template);
        }
    });
});

1 个答案:

答案 0 :(得分:4)

您不能简单地从包含页面的DOM访问textarea,因为实际的WYSIWYG编辑器位于带有.wysihtml5-sandbox的iFrame中。因此,要访问iFrame的DOM并对其进行修改,我们必须首先访问iFrame DOM:

  $('.wysihtml5-sandbox').contents() 
  //Now we have the iFrame DOM to apply selectors to

  $('.textarea', $('.wysihtml5-sandbox').contents())
  //Now we have access to the textarea which contains the editor's current text

  $('.textarea', $('.wysihtml5-sandbox').contents()).append('Hello World!')
  //Now we have appended content to the editor view, the original goal 

额外的东西:

$('.textarea', $('.wysihtml5-sandbox').contents()).removeClass('placeholder')
//Stops the text from being formatted as a placeholder (i.e. grayed out)
$('.textarea', $('.wysihtml5-sandbox').contents()).empty()
//Remove the existing placeholder text by emptying the textarea content