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 );
});
});
たとえば、「ipsum」をクリックすると、JS は「Lorem」を前のテキストとして、「data sid amet」を「ipsum」の後のテキストとして警告します。
お役に立てれば!フィドルを実行して、私の意味を確認することもできます。