gpt4 book ai didi

javascript - codemirror:无需对话即可搜索并突出显示多个单词

转载 作者:行者123 更新时间:2023-11-29 20:43:45 27 4
gpt4 key购买 nike

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

  1. 搜索并突出显示多个字符串
  2. 我希望能够迭代找到的每个匹配项并打印其行号。
  3. 我想以编程方式进行,不想像示例中那样使用对话框 https://codemirror.net/demo/search.html

问题:

  1. 在 while 循环中只选择最后一场比赛,之前的比赛被清除,但我也希望它像 https://codemirror.net/demo/search.html 一样突出显示为黄色

JSFIDDLE: https://jsfiddle.net/bababalcksheep/p7xg1utn/30/

代码:

$(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一次只能高亮一个连续的子串。相反,您可以使用 markText方法,传入 cursor.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;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.44.0/codemirror.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.44.0/addon/search/searchcursor.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.44.0/codemirror.min.css">

<div class="container">
<p><strong>Objective:</strong></p>
<p>Find/search and highlight both words <strong>alpha</strong> and <strong>beta</strong> in codemirror editor</p>
<button id="search" type="button" class="btn btn-primary">Search and highlight</button>
<br><br>
<textarea id="code" name="code" rows="8">Text line
alpha 1
Text line
Text line
alpha 2
Text line
Text line
beta 1
Text line</textarea>

关于javascript - codemirror:无需对话即可搜索并突出显示多个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54957259/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com