分配CKEditor到动态创建的文本框元素



我有一个表结构,其中CKEditor附加到一个表td。像这样:

:

<table class="table table-striped table-condensed" id="questionDetails">
<thead>
<tr>
<th>Question Name</th>
<th>Options</th>
<th>Answers</th>
</tr>
</thead>
<tbody id="tbody">
<tr>
<td class="col-xs-3">
<input type="text" class="txtQuestionName form-control" name="txtQuestionName" value="" />
&nbsp;
</td>
<td class="col-xs-3">
<input type="text" class="txtOptions form-control" name="txtOptions" value="" />
<span class="addOptions">(+)</span> &nbsp;
</td>
<td class="col-xs-3">
<input type="text" class="txtAnswers form-control" value="" />
<span class="addAnswers">(+)</span> &nbsp;
</td>
<td class="col-xs-12">
<input type="text" class="txtExplanation form-control editor1" name="editor1" />
&nbsp;
</td>
<td>
<a href="javascript:void(0);" id="btnAdd" class="btn btn-primary">Add</a>
</td>
</tr>
</tbody>
</table>

jQuery:

<script src="~/ckeditor/ckeditor.js"></script>
<script type="text/javascript">
//Initialize CKEditor by giving id of text area
CKEDITOR.replace('editor1');
//Get each instance of CKEditor
for (instance in CKEDITOR.instances) {
//update element
CKEDITOR.instances[instance].updateElement();
}
//Add row to the table
$("#btnAdd").click(function () {
$("#questionDetails").append('<tr><td><input type="text" class="txtQuestionName form-control" class="form-control" /></td> <td><input type="text" class="txtOptions form-control" /><span class="addOptions">(+)</span></td> <td><input type="text" class="txtAnswers form-control" /> <span class="addAnswers">(+)</span></td><td><input type="text" class="txtExplanation form-control editor1" name="editor1" /></td> <td><a href="javascript:void(0);" class="btn btn-danger remCF">Remove</a></td> &nbsp;</tr>');
});
</script>

上面的代码在默认情况下加载页面时工作。但是当我尝试使用jQuery动态添加更多行到表时,这不会创建或分配CKEditor到那个输入元素。除了编辑器之外,其他输入元素都被创建了。我能不能给CKEditor赋值到表中动态创建的行并从中获取所有值?

下面是一个工作示例。你必须确保给所有编辑器一个唯一的ID

<div>
<textarea id="editor1"></textarea>
</div>
<div>
<button type="button" id="btnAdd">Add CKEditor</button>
</div>
<div id="questionDetails">
</div>
<script type="text/javascript" src="~/ckeditor/ckeditor.js"></script>
<script type="text/javascript">
//the inital editor
CKEDITOR.replace('editor1');
//use an number to make the id's of the new editors unique
var index = 2;
//Add row to the table
$("#btnAdd").click(function () {
//create the new id
var newEditor = 'editor' + index;
//append some html
$("#questionDetails").append('<textarea id="' + newEditor + '"></textarea>');
//init the new editor
CKEDITOR.replace(newEditor);
//increment
index++;
});
</script>

如果要读取内容,只需循环实例并使用getData()

获取数据
$("#btnRead").click(function () {
for (var i in CKEDITOR.instances) {
alert(CKEDITOR.instances[i].getData());
}
});

最新更新