3

I have obtained the currently selected content in a web page, using Javascript.

For example sample HTML for a web page is given below--

    <div id="divText">Text 1
        <div id="divText1_1">Text 1_1</div>
        <div id="divText1_2">Text 1_2</div>
    </div>

Now, the user has selected text "Text 1_2" - from the HTML above, we can see that this is the second div within the div named "divText"- how do I get this information using Js code? The info that I want- "divText1_2" is the second div within its parent HTML element. ( I want to know the number of divs that occurred before "divText1_2"- when text within "divText1_2" has been selected by the user)...

4

2 に答える 2

0

必要な情報がそのdivのテキストだけである場合は、次を試してください。

 $(document).ready(function () {

    alert($("#divText1_2").text());
});
于 2012-07-28T20:04:34.573 に答える
0

ユーザーがブラウザからテキストを選択したときにdividがわからない場合は、jqueryを使用してhtml要素を見つけることができます。例:

dom = $('*:contains("Text 1_2")');

次のようなdomの配列を作成します。

dom_array = []
for( var j=0; j<dom.length; j++){
  dom_array[j] = dom[j];
}

これで、配列の最後の要素は、選択したテキストを含む正確なhtml要素になります(選択したテキストが1回だけ発生すると仮定)

selected_id = dom_array[dom_array.length-1].id // 

var a = document.getElementById("divText");
    var arr = [];
    var div = document.getElementById("selected_id"); 
    for( var i=0; i<a.length; i++){
      arr[i] = a[i];
    }
    console.log(arr.indexOf(div));
于 2012-07-28T20:04:50.557 に答える