2014-12-05 34 views
1

正如標題所說,假設我在某個div中有一個帶有文本的網站,有沒有辦法突出它的某些部分並知道它是哪一個?如果文本中出現了4個「something」這個單詞,並且我強調了第3個,那麼如何使用Javascript/JQuery獲取這些信息?如何查找出現突出顯示的字符串的次數,以及出現的次數?

+0

取決於...你可以添加一個類,即。 「.highlighted」,然後用JS拉出所有的單詞,轉換爲數組然後檢查整個。 – Will 2014-12-05 18:17:44

回答

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

你可以:

  1. 得到突出顯示的文本Get the Highlighted/Selected text
  2. 得到父元素的所有文字,或者頁面的所有文字,或任何你想要得到的
  3. 分詞的文本的所有文本
  4. 檢查同一單詞的occurances
相關問題