0

http://jsfiddle.net/tZVsS/72/

如果你双击类的前两个元素中的任何一个,.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, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");

        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>
4

1 回答 1

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, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");

            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]);
    }
})();
于 2013-01-18T22:05:05.657 回答