如何使用jquery

时间:2015-11-24 11:01:07

标签: javascript jquery html

您好我的目标是获取可编辑动态div的选定内容

下面是我的代码



function getSelectionHtml() {
  var html = "";

  if (typeof window.getSelection != "undefined") {
    var sel = window.getSelection();

    if (sel.rangeCount) {
      var container = document.createElement("div");

      for (var i = 0, len = sel.rangeCount; i < len; ++i) {
        container.appendChild(sel.getRangeAt(i).cloneContents());
      }

      html = container.innerHTML;
    }
  } else if (typeof document.selection != "undefined") {
    if (document.selection.type == "Text") {
      html = document.selection.createRange().htmlText;
    }
  }
  
  alert({
    title: "Copied Text",
    text: '"' + html + '"',
    timer: 10000
  });
}

// The alert() function is disabled in Stack Snippets.
function alert(opts){swal($.extend({type:"info",confirmButtonText:"Close"},opts));}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css" rel="stylesheet" />


<div id="myarea" contenteditable="true">Lorem ipsum dolor sit amet</div>
<button onclick="getSelectionHtml();">Get HTML</button>
&#13;
&#13;
&#13;

如果页面加载时出现文本,则上面的代码工作正常。但是当我动态地将div附加到主div时。选择那里的文字并没有获得文本

0 个答案:

没有答案