正如標題所說,假設我在某個div中有一個帶有文本的網站,有沒有辦法突出它的某些部分並知道它是哪一個?如果文本中出現了4個「something」這個單詞,並且我強調了第3個,那麼如何使用Javascript/JQuery獲取這些信息?如何查找出現突出顯示的字符串的次數,以及出現的次數?
1
A
回答
1
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);
});
});
+0
我認爲這是按照我的意圖工作的。謝謝! – user1025725 2014-12-05 22:32:53
1
你可以:
- 得到突出顯示的文本Get the Highlighted/Selected text
- 得到父元素的所有文字,或者頁面的所有文字,或任何你想要得到的
- 分詞的文本的所有文本
- 檢查同一單詞的occurances
相關問題
- 1. Java查找次數出現的次數
- 2. 計數字符串的出現次數
- 3. 突出顯示字符串的所有出現次數 - 未正確遞增
- 4. 使用Ruby查找字符串中字符的出現次數
- 5. 查找字符串中出現字符的次數
- 6. 查找字符串中字符的最後出現次數
- 7. 如何在UIWebView中突出顯示第一次出現的字符串?
- 8. 如何顯示字符串中多次出現的字符?
- 9. 如何找到子的出現次數字符串中的
- 10. 查找python中字符串中單詞的出現次數3
- 11. 查找所有子字符串的出現次數和位置
- 12. 查找字符串的出現次數並使用C#替換
- 13. 查找多個文件中字符串出現的次數
- 14. 在字符串中查找「Y」或「N」的出現次數
- 15. 查找HTML文件中字符串的確切出現次數
- 16. 查找矩陣中字符串的出現次數
- 17. 使用子串查找出現次數
- 18. 串的出現次數
- 19. MS Word VBA,突出顯示字符串第一次出現的代碼
- 20. 如何查找一個字符串中字符出現的總次數?
- 21. 底部顯示的「當前出現次數/總次數出現」的Vim搜索
- 22. 檢查字符串中出現字符的次數
- 23. 字符串中出現次數
- 24. 找到數組列表中字符串出現的次數
- 25. Bash:從第一次出現的字符到第二次出現的字符串
- 26. C++:查找字符串中字符的最後一次出現
- 27. 在只出現一次的字符串中查找字符
- 28. 查找字符串中字符的最高連續出現次數拋出字符串索引超出範圍
- 29. 查找出現奇數次的元素
- 30. 查找行的出現次數
取決於...你可以添加一個類,即。 「.highlighted」,然後用JS拉出所有的單詞,轉換爲數組然後檢查整個。 – Will 2014-12-05 18:17:44