codemirror:搜索并突出显示多个单词而无需对话框

问题描述 投票:2回答:1

目标:我使用codemirror作为编辑。我想要

  1. 搜索并突出显示多个字符串
  2. 我希望能够迭代找到的每个匹配数并打印其行号。
  3. 我想以编程方式执行此操作,并且不希望使用对话框,例如qazxsw poi

问题:

  1. 在while循环中只选择了最后一个匹配,之前的那些被清除,但我也希望它像https://codemirror.net/demo/search.html那样突出黄色

的jsfiddle:https://codemirror.net/demo/search.html

码:

https://jsfiddle.net/bababalcksheep/p7xg1utn/30/
javascript codemirror
1个回答
2
投票

调用$(document).ready(function() { // var editor = CodeMirror.fromTextArea(document.getElementById("code"), { mode: "text/html", lineNumbers: true, }); // function search(val) { var cursor = editor.getSearchCursor(val); while (cursor.findNext()) { editor.setSelection(cursor.from(), cursor.to()); console.log('found at line ', cursor.pos.from.line + 1); } } // $('#search').click(function(event) { event.preventDefault(); search(/^alpha|^beta/); }); // }); 一次只能突出显示一个连续的子字符串。相反,您可以使用setSelection方法,传入markTextcursor.from()以获取要突出显示的位置:

cursor.to()
$(document).ready(function() {
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
    mode: "text/html",
    lineNumbers: true,
  });
  function search(val) {
    var cursor = editor.getSearchCursor(val);
    while (cursor.findNext()) {
        editor.markText(
          cursor.from(),
          cursor.to(),
          { className: 'highlight' }
        );
    }
  }
  //
  $('#search').click(function(event) {
    event.preventDefault();
    search(/^alpha|^beta/);
  });
});
.CodeMirror {
  border-top: 1px solid black;
  border-bottom: 1px solid black;
  height: 200px;
}
.highlight {
  color: orange;
}
© www.soinside.com 2019 - 2024. All rights reserved.