如何使用 Javascript 设置 CodeMirror 编辑器的值?
我尝试在以下代码中设置 id4:
<div id="id1">
<div id="id2">
<div id="id3">
<textarea id="id4"></textarea>
</div>
</div>
</div>
通过使用此代码:
document.getElementById('id4').value = "...";
和此:
document.getElementById('id3').getElementsByTagName('textarea')[0].value = "...";
但没有任何效果。
更新:
textarea
被 CodeMirror 编辑器取代。我如何为其设置值?
非常感谢您的帮助!
I try to set id4
in the following code:
<div id="id1">
<div id="id2">
<div id="id3">
<textarea id="id4"></textarea>
</div>
</div>
</div>
By using this code:
document.getElementById('id4').value = "...";
And this:
document.getElementById('id3').getElementsByTagName('textarea')[0].value = "...";
But nothing works.
UPDATED:
The textarea
is replaced by CodeMirror editor. How do I set value to it?
Thanks a lot for the help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
自 3.0 发布以来,执行此操作的方式略有变化。现在是这样的:
The way to do this has changed slightly since the release of 3.0. It's now something like this:
我喜欢例子。试试这个:
I like examples. Try this:
正如你所说,textarea 被 Codemirror 取代。但它被类为“CodeMirror”的元素所取代。您可以使用 querySelector 来获取元素。当前的 CodeMirror 实例(及其方法)附加到此元素。所以你可以这样做:
As you said, the textarea is replaced by Codemirror. But it is replaced by an element with the class "CodeMirror". You can use querySelector to get the element. The current CodeMirror instance (and its methods) is attached to this element. So you can do:
CodeMirror ~4.6.0 你可以这样做,假设你有一个 codemirror 对象:
CodeMirror ~4.6.0 you can do this, assuming you have a codemirror object:
您拥有的代码应该可以工作。失败的最可能的解释是元素在运行时不存在。如果是这样,解决方案是:
之前)
onload
事件处理程序的函数)The code you have should work. The most likely explanation for it failing is that the elements do not exist at the time you run it. If so the solutions are to either:
</body>
)onload
event handler)这对我的(相当旧的)版本的 CodeMirror 有效:
This has worked for my (pretty old) version of CodeMirror:
editor.setValue("YOUR_VALUE");
editor.setValue("YOUR_VALUE");