2017-04-06 59 views
0

我有以下HTML結構:觸發onmouseup元素正確

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

所以這段代碼只是控制檯日誌選定的文本。

但是我有一個問題 - 當我點擊不是我<p>元素,只是在文件 - 然後我將鼠標移動選擇文本控股左鍵我不能讓父母div的ID,因爲

var target=event.target; 

目標成爲文檔元素

+3

爲什麼不'$( 「P」)mouseup'? – sweaver2112

回答

0

更改$(document).mouseup($("#parent").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