如何从窗口更新文本选择版本

时间:2015-01-23 17:00:40

标签: jquery

使用用户鼠标选择,我收到selected文本,并更新到容器。当用户点击(选择已发布)时,我想将selected文本更新为空。

我试过这种方式,但似乎行不通,

    $('#tenderContent').on('mouseup', '.tenderdocument', function(e){
    e.stopPropagation();
    if($.trim(window.getSelection().toString()).length) {
       $('#text').text(window.getSelection().toString());
    }
});

$('#tenderContent').on('click', '.tenderdocument', function () {
    var selection = $.trim(window.getSelection().toString());
    if(!selection) {
        console.log("there is no selection"); //nothing consoles after selection released
        $.event.trigger({type:'textUnselected'});
    }
}); 

Live

2 个答案:

答案 0 :(得分:1)

您只需要在更新前删除检查选择的if条件:

$('#tenderContent').on('mouseup', '.tenderdocument', function (e) {
    e.stopPropagation();
    $('#text').text(window.getSelection().toString());
});

<强>更新

如果要在清除选择时运行特定功能,请尝试以下操作:

$('#tenderContent').on('mouseup', '.tenderdocument', function (e) {
    e.stopPropagation();
    if ($.trim(window.getSelection().toString()).length) {
        $('#text').text(window.getSelection().toString());
    }
    else {
        $('#text').empty();
        console.log("there is no selection"); //nothing consoles after selection released
        $.event.trigger({ type:'textUnselected' });
    }
});

Updated fiddle

答案 1 :(得分:1)

您只关注.tenderdocument#tendercontent元素的点击次数,如果点击发生在您之外,您将不会被注意到。

尝试在文档级别绑定以捕获所有点击,如下所示:

$('#tenderContent').on('mouseup', '.tenderdocument', function(e){
    e.stopPropagation();
    if($.trim(window.getSelection().toString()).length) {
       $('#text').text(window.getSelection().toString());
    }
});

$(document).on('click', function (e) {
    var selection = $.trim(window.getSelection().toString());
    if(!selection && !$('#text').is(':empty')) {
        $('#text').empty();
        alert('text emptied!');
    }
}); 

JSFiddle:http://jsfiddle.net/hdaj1t7w/3/