Jquery:选择文本时运行代码

时间:2010-10-17 11:47:59

标签: javascript jquery

我有一个像这样llokes的HTML文档:

<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有一个.select() event,这使得这很容易做,但看起来,当选定的文本在输入或文本区域内时,它可以工作。

这是我尝试过的代码:

$(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');
            }
        );

    }
);

什么都没发生。

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

1 个答案:

答案 0 :(得分:4)

jQuery核心没有任何内容,但有some plugin options

您的代码如下所示:

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

You can test it out here