2010-07-21 38 views
1
A simple tool to store and display texts longer than a few lines. 
The search button<div id="xyz">will highlight all</div> the words matching the name of objects that are members of the classes listed in searchedClasses, 
itself a member of the KeySet class. The highlighted words are hypertext. 

我想檢索由div-xyz標記包圍的字符。
example output.
....搜索按鈕將突出顯示所有的話.....包圍特定標記的特定字符的連接

我能夠通過以下來獲得當前div標籤的文本。

function myDivHTML(valueName){ 
    if((obj = document.getElementById(valueName)) && obj != null){ 
     return obj.innerHTML; 
    }  
} 

我試圖與元素的性質offsetParent - 但也有很多可能性,例如div標籤可能就可以大膽標籤&大膽的標籤裏面可以是對標籤&內等。

我該怎麼做才能得到周圍的文字?限制可能是10,20個字符。

編輯:

周圍的文本指 - >文本左側10或20個字符和右側10或20個字符。

+0

定義 「周圍的文本」。 – Tomalak 2010-07-21 10:02:25

+0

@Tomalak - 請檢查示例和編輯問題。 – 2010-07-21 10:04:26

回答

2

要做到這一點,最簡單的方法就是將內部div的內容用不透明的字符串包裹在任何一邊,然後在整個段落中使用正則表達式來查找您添加的標記以及所需的字符數側。事情是這樣的:

var full, result, 
    // textContent for w3 compliance, innerText for IE 
    txt = "textContent" in document.body ? "textContent" : "innerText", 
    // Get references to both divs and store the current text of `xyz` 
    out = document.getElementById("outer"), 
    xyz = document.getElementById("xyz"), 
    old = xyz[txt]; 

// wrap the inner text with something we can easily search for: 
xyz[txt] = "||||" + xyz[txt] + "||||"; 

// Get the whole text, change the DOM text back to what it was 
full = out[txt]; 
xyz[txt] = old; 

// Find the text with our markers and surrounding text: 
result = /.{0,10}\|{4}.*?\|{4}.{0,10}/.exec(full); 

alert(result[0]); 
// -> "ch button ||||will highlight all|||| the words" 

// Finally, replace your wrapping strings: 
result = result[0].replace(/\|{4}/g, ""); 

alert(result); 
// -> "ch button will highlight all the words" 

您可能要稍微調整正則表達式,這樣它匹配,也就是說,前兩和內部串後,整個單詞。


http://www.jsfiddle.net/Sy4rT/

+0

是否可以在移動Safari(iPhone)上運行此JavaScript? – 2010-07-21 10:47:25

+0

@sugar:沒有理由不應該在iPhone Safari上工作,但我會檢查你。 **編輯**工作正常。理論上,它應該可以在任何支持Javascript和innerText/textContent的現代瀏覽器中使用。行! – 2010-07-21 11:03:25

+0

行!讓我試試這個。 – 2010-07-21 11:17:07

相關問題