0

私はwebviewで作業していて、htmlページをwebviewにロードしているので、ここで行き詰まりました.javascript.hereを使いたいです. 私は正確に何が必要かを説明しています:私はこのようなhtmlデータを持っています-

「私は「ウィジェット」という単語を選択しました。しかし、選択が「赤」または「青」のどちらの後にあるのか知りたいのですが、これは可能ですか?インターネットでアドバイスを探していましたが、問題が発生しています。答えを見つける」

したがって、上記のテキストから、「 selection is after 」というテキストを選択したとします(太字で示されています)。この単語の前の単語と、その行のこの単語の後の単語のみが必要です。2行目で選択すると、その行の単語の前のすべての前の単語と、その行の選択した単語の後のすべての単語が必要になり、選択した単語が行の先頭にある場合は、前の単語をnullとして返し、残りの単語を返します選択した単語の後から行末まで、最後の単語と同様に、その逆

JavaScript を使用してそれを実現する方法を教えてください。

4

2 に答える 2

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 );                                                     
});
});

たとえば、「ipsum」をクリックすると、JS は「Lorem」を前のテキストとして、「data sid amet」を「ipsum」の後のテキストとして警告します。

お役に立てれば!フィドルを実行して、私の意味を確認することもできます。

于 2013-04-05T11:43:46.527 に答える
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
于 2013-04-05T11:30:47.170 に答える