jQuery:在div中获取选定文本的html源

问题描述:

我想获取div中选定文本的HTML源,并发出警报.

I want to get HTML source of select text in div and alert that.

这是我的代码:

if (!window.x) {
    x = {};
}
x.Selector = {};
x.Selector.getSelected = function() {
    var t = '';
    if (window.getSelection) {
        t = window.getSelection();
    } else if (document.getSelection) {
        t = document.getSelection();
    } else if (document.selection) {
        t = document.selection.createRange().text;
    }
    return t;
}

$(function() {

    $(document).bind("mouseup", function() {
        var mytext = x.Selector.getSelected();
        alert(mytext);
    });

来源

但是返回的文字是纯文本.

But that return text plain.

有什么办法吗?

感谢您的帮助.

http: //www.codingforums.com/showthread.php?t=154848#post762994 建议如下:

function selHTML() {

    if (window.ActiveXObject) {
        var c = document.selection.createRange();
        return c.htmlText;
    }

    var nNd = document.createElement("p");
    var w = getSelection().getRangeAt(0);
    w.surroundContents(nNd);
    return nNd.innerHTML;
}

Google很好(无论如何):-)

Google is good (often anyway) :-)

演示: http://jsfiddle.net/rR8Sh/1/ 我添加了纯文本选择,以防标签未完全选中,并使用跨度(而不是p)来避免添加换行符.仍然会添加空的<span>;我想不出办法避免这种情况.

Demo: http://jsfiddle.net/rR8Sh/1/ I added plain text selection in case a tag is incompletely selected and used span instead of p to avoid adding a line break. It will still add the empty <span> though; I couldn't think of a way to avoid that.