我在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阿梅特」視後「文字」的文字。
希望這會有所幫助!您也可以運行小提琴來了解我的意思。
但在我的情況下ids和節點是不同的它不總是從段落它可以從標題標籤和任何其他標籤,所以如何得到那??? – Ravi 2013-04-06 03:48:48