jQuery:在div中获取选定文本的html源 [英] jQuery : get html source of selected text in div

查看:118
本文介绍了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.

这篇关于jQuery:在div中获取选定文本的html源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆