2017-04-06 8 views
0

私はHTML構造次き:トリガー正しく

<div id="grandparent"> 
    <div id="parent"> 
      <p> 
       high light me with mouse!! highlight me with mouse!!highlight me with mouse!! 

      </p> 

</div> 
</div> 

をそして私は、このコードをJSあります

$(document).mouseup(function (event) { 
     var target=event.target; 
     target=$(target); 
     var parent = target.parent(); 
     console.log(parent.parent().attr("id")); 
      if (window.getSelection) { 
      var selection = window.getSelection(); 
      selectedText = selection.toString(); 
       console.log(selectedText); 
      } 
     }); 

ように、コードのこの作品は、単にテキストを選択したログを慰めます。

しかし、私は問題を抱えている - 私は

var target=event.target; 
ので、親のdivのIDを取得することはできませんし、私は左のボタンを押し、テキストを選択するためにマウスを移動 - 私は私の <p>要素にだけ、ドキュメントにない]をクリックしたときに

対象が文書要素

+3

なぜ '$( "P")mouseup'? – sweaver2112

答えて

0

$("#parent").mouseup(の場合は$(document).mouseup(に変更されます。

コード:

$("#parent").mouseup(function (event) { 
 
    var target=event.target; 
 
    target=$(target); 
 
    var parent = target.parent(); 
 
    console.log(parent.parent().attr("id")); 
 
    if (window.getSelection) { 
 
    var selection = window.getSelection(); 
 
    selectedText = selection.toString(); 
 
    console.log(selectedText); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="grandparent"> 
 
    <div id="parent"> 
 
      <p> 
 
       high light me with mouse!! highlight me with mouse!!highlight me with mouse!! 
 

 
      </p> 
 

 
</div> 
 
</div>

+0

動的に作成された$( "#parent")がわかりません – user2950593

関連する問題