javascript - jQuery:如何包装选定的文本

标签 javascript jquery html replace getselection

我想使用以下函数获取当前选定的文本(来源:javascript replace selection all browsers)。

在我的例子中,我不想替换选定的文本,而是想在它前后添加一些东西,主要是 HTML 标签(通过单击按钮)。

示例: 所选文本 = 你好 新文本 (html) = <u>Hello</u>

获取选中文本的代码:

  function replaceSelection(html) {
        var sel, range, node;

        if (typeof window.getSelection != "undefined") {
            // IE 9 and other non-IE browsers
            sel = window.getSelection();

            // Test that the Selection object contains at least one Range
            if (sel.getRangeAt && sel.rangeCount) {
                // Get the first Range (only Firefox supports more than one)
                range = window.getSelection().getRangeAt(0);
                range.deleteContents();

                // Create a DocumentFragment to insert and populate it with HTML
                // Need to test for the existence of range.createContextualFragment
                // because it's non-standard and IE 9 does not support it
                if (range.createContextualFragment) {
                    node = range.createContextualFragment(html);
                } else {
                    // In IE 9 we need to use innerHTML of a temporary element
                    var div = document.createElement("div"), child;
                    div.innerHTML = html;
                    node = document.createDocumentFragment();
                    while ( (child = div.firstChild) ) {
                        node.appendChild(child);
                    }
                }
                range.insertNode(node);
            }
        } else if (document.selection && document.selection.type != "Control") {
            // IE 8 and below
            range = document.selection.createRange();
            range.pasteHTML(html);
        }
    }

调用函数的代码:

replaceSelection('<span><font color="red">hoho</font></span>');

谁能告诉我如何通过修改以上内容来实现这一点?

Tim,非常感谢您对此提供的帮助。

最佳答案

jQuery 的 append() 和 prepend() 应该可以解决问题。

$(".my-span").prepend("<u>").append("</u>");

HTML:

<div>
  <span class="my-span">Hello</span>
</div>

关于javascript - jQuery:如何包装选定的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19973250/

相关文章:

javascript - 如何通过 ajax 调用将数据添加到图表中?

php - 根据服务器请求将 PHP header 发送到 html 文件?

javascript - 从 php 调用 Javascript 函数

javascript - 搜索字符串但忽略标签

javascript - 用于将更高的内联 block div 放入其容器行的 jQuery 选择器

html - 是否可以在 SVG 中创建发光效果

html - 如何在 HTML 中拉伸(stretch)视频的宽度?

javascript - 即时选择 AuthGuard 类型

JavaScript 与 ASP.NET 确认

javascript - Fullpage.js 的导航问题,未显示事件状态