如果您使用类.code
双击前两个元素中的任何一个,您会注意到setOptions仅应用于具有类.code
的最后一个元素。我需要做的是当你双击每个单独元素时要应用于该元素的setoption,为什么这不起作用以及可以做些什么来解决它
(function () {
var codes = document.getElementsByClassName("code");
for (i = 0; i < codes.length; i++) {
var $this = codes[i];
var $unescaped = $this.innerHTML.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
var isspan = $this.nodeName.toLowerCase() == "span";
$this.innerHTML = "";
if (isspan) {
$this.style.display = "inline-block"
} else {
$this.style.display = "inline"
}
var editor = new CodeMirror($this, {
value: $unescaped,
mode: 'javascript',
lineNumbers: false,
readOnly: true
});
$this.ondblclick = function () {
editor.setOption("readOnly", false);
editor.setOption("lineNumbers", true);
}
}
})();
HTML在下方,请注意:它没有多大用处,而是回溯我在小提琴上所做的事情,以便更好地理解
Some code <span class="code inline">function inline() { alert('inline code') }</span> inside
a sentence.
<div class="code">function test() { return false; }</div>
答案 0 :(得分:1)
只是范围问题
更新小提琴:http://jsfiddle.net/tZVsS/73/
(function () {
var codes = document.getElementsByClassName("code");
for (i = 0; i < codes.length; i++) {
(function ($this) {
var $unescaped = $this.innerHTML.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
var isspan = $this.nodeName.toLowerCase() == "span";
$this.innerHTML = "";
if (isspan) {
$this.style.display = "inline-block"
} else {
$this.style.display = "inline"
}
var editor = new CodeMirror($this, {
value: $unescaped,
mode: 'javascript',
lineNumbers: false,
readOnly: true
});
$this.ondblclick = function () {
console.log($this);
editor.setOption("readOnly", false);
editor.setOption("lineNumbers", true);
}
})(codes[i]);
}
})();