2010-10-17 54 views
1

我有一个像这样llokes的HTML文档:Jquery:选择文本时运行代码

<div class="this_can_be_selected">Some text here</div> 
<div>No text in the div above is selected</div> 

<div class="this_can_be_selected">Some text here</div> 
<div>No text in the div above is selected</div> 

<div class="this_can_be_selected">Some text here</div> 
<div>No text in the div above is selected</div> 

我希望将文本No text in the div above is selected更改为Some text in the div above is selected时,猜猜看,上面div中的一些文本被选中了:)

jQuery has一个.select() event,这将使这很容易做,但似乎,当选定的文本在输入或textarea内时,它工作。

这是我尝试过的代码:

$(document).ready(function() 
    { 

     //Some text inside div is selected 
     $('DIV.this_can_be_selected').select 
     (
      function() 
      { 
       alert('Something is selected!'); 
       $(this).next().html('Some text in the div above is selected'); 
      } 
     ); 

    } 
); 

什么都没发生。

有没有办法解决这个问题?

回答

4

jQuery核心没有这个东西,但有some plugin options

您的代码应该是这样的:

$(function() { 
    $(document).bind('textselect', function(e) { 
    alert('Selected Text: ' + e.text); 
    });  
}); 

You can test it out here

+0

谢谢!它做到了! – 2010-10-17 12:24:16