gpt4 book ai didi

javascript - 我如何找到突出显示的字符串出现了多少次,以及它出现在哪一次?

转载 作者:行者123 更新时间:2023-11-30 17:09:21 25 4
gpt4 key购买 nike

正如标题所说,假设我有一些网站,其中一些 div 内有文本,有没有办法突出显示它的某些部分并知道它是哪次出现的?如果文本中出现了 4 次单词“something”,我突出显示了第 3 次,我如何使用 Javascript/JQuery 获取该信息?

最佳答案

http://jsfiddle.net/g09g35xa/6/

这是一个似乎有效的方法。突出显示您想要的字符串,当您单击按钮时,它会提醒 div 中突出显示的单词的索引。

标记:

<div id="theDiv">
<p>The quick brown quick fox jumps over the lazy dog</p>
</div>
<br />
<input id="findIndex" type="button" value="Find Index Of Highlighted String" />

还有 JS:

function getSelectedHTML() {
try {
if (window.ActiveXObject) {
var c = document.selection.createRange();
return c.htmlText;
}

return getSelection().getRangeAt(0).toString();
} catch (e) {
if (window.ActiveXObject) {
return document.selection.createRange();
} else {
return getSelection();
}
}
}

function surroundSelectedElement() {
var nNd = document.createElement("span");
nNd.setAttribute("id","actualSelectedElement");
var w = getSelection().getRangeAt(0);
w.surroundContents(nNd);
}

$(function() {
// save originalHtml to reset later
var originalHtml = $("#theDiv").html();
$("#findIndex").click( function() {
// get the selected string
var selectedText = getSelectedHTML();
if(selectedText === '')
return;

// surround the selected area with a span, id = actualSelectedElement
surroundSelectedElement();

// build Regex to find all occurrences of string that was selected
var re = new RegExp(selectedText, "g");

// replace instances of string with span tags, class = selectedText
$("#theDiv").html($("#theDiv").html().replace(re, "<span class='selectedText'>" + selectedText + "</span>"));

// the actual one selected is contained within a span with id=actualSelectedElement, so get all spans with class=selectedText and find the index of the one with the extra span actualSelectedElement
var index = $('span.selectedText').index($('span#actualSelectedElement span.selectedText'));

alert(index);

// reset the html back to original
$("#theDiv").html(originalHtml);
});
});

关于javascript - 我如何找到突出显示的字符串出现了多少次,以及它出现在哪一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27322148/

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