2013-04-05 54 views
0

我正在使用webview並在webview中加載html頁面,所以在這裏我被卡住了某處,我想使用javascript.here。我explaing什麼,我到底需要如下: 我有喜歡這 -如何獲得javascript或jquery中的環繞單詞?

HTML數據「我選擇的詞‘窗口小部件紅’不過,我想知道,如果選擇後。」 「或‘藍色’。這可能嗎?我一直在網上淘一些建議,我無法找到答案」

所以從上面的文字想我選擇的文本「選擇後「(以粗體顯示)我需要在此單詞之前的前面的單詞以及該單詞之後的單詞。假設我在第2行中選擇,所以我需要在該行之前的該行中的前一個單詞以及該行中所選單詞之後的所有單詞,並且如果所選單詞在行首,則返回前一個單詞爲空並且剩餘單詞在選定的字之後 - 對於最後一個字類似的末尾行反之亦然

請告訴我們如何使用JavaScript實現它?

回答

0

我在Selecting text before and after word

創造了一個的jsfiddle的解決方案首先,我創建了一個段落來保存文本被選中

<p id="yourTextContainer">Lorem ipsum data sid amet</p> 

然後,在JavaScript中,我將該段落分成幾個跨度,將每個單詞的索引放在name屬性中。然後,當一個單詞被點擊時,它使用索引來返回之前的所有單詞,以及之後的所有單詞。

var textindex; 
var textbefore; 
var textafter; 

$(document).ready(function(){ 
var words=$("#yourTextContainer").text().split(' '); 
$("#yourTextContainer").html(""); 

$.each(words, function(i,val){ 
//wrap each word in a span tag 
$('<span name="'+ i+'"+ />').text(val +" ").appendTo("#yourTextContainer"); 

}); 

$("#yourTextContainer span").live("click",function(event){event.stopPropagation(); 
                  $("#yourTextContainer span").css("background-color","white"); 
$(this).css("background-color","blue"); 

//gets the text of clicked span tag 
var textselected = $(this).text(); 
textindex = $(this).attr("name");               
    alert("You just selected "+textselected+" index " + textindex); 
textbefore= ""; 
textafter = "";               
    $("span").each(function (index) { 
     // alert("LOOPING INDEX " + index); 
     if (index<(textindex)) 
      textbefore = textbefore + $(this).text() + " "; 
     if (index>(textindex)) 
      textafter = textafter + $(this).text() + " "; 
     }); 
    alert("Text before is "+textbefore); 
    alert("Text after is "+textafter);              
}); 
}); 

例如,如果你點擊「文字」,JS的警報,「排版」爲文本之前,和「數據SID阿梅特」視後「文字」的文字。

希望這會有所幫助!您也可以運行小提琴來了解我的意思。

+0

但在我的情況下ids和節點是不同的它不總是從段落它可以從標題標籤和任何其他標籤,所以如何得到那??? – Ravi 2013-04-06 03:48:48

0

怎麼樣使用match用正則表達式:

var pattern = /^(.+)(selection is after)(.+)$/; 
match = "hello selection is after goodbye".match(pattern) 

match[1] // hello 
match[2] // selection is after 
match[3] // goodbye 
+0

我需要從當前行的開始和單詞到當前行結束的前一個單詞,它會對我有用嗎? – Ravi 2013-04-05 11:36:51

+0

你只需要單個單詞。在比賽選擇之前一個緊跟在之後?如果你想在同一行上的所有單詞前後,那麼上面的表達式就可以工作。 '^'和'$'是行錨的開始和結束。 – osahyoun 2013-04-05 11:43:55

+0

okk我會更新你,如果它會工作 – Ravi 2013-04-05 13:00:19

相關問題