Javascript toString()返回空字符串,不管所选范围如何

Javascript toString()返回空字符串,不管所选范围如何,javascript,range,selection,Javascript,Range,Selection,我尝试使用以下代码在单击时选择元素的文本: var selection = window.getSelection(); var range = document.createRange(); range.selectNodeContents(element); selection.removeAllRanges(); selection.addRange(range); 尽管文本高亮显示,但使用Ctrl+C将空字符串复制到剪贴板上。检查所选内容。toString()也会返回空字符串。知道为什

我尝试使用以下代码在单击时选择元素的文本:

var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);

尽管文本高亮显示,但使用Ctrl+C将空字符串复制到剪贴板上。检查所选内容。toString()也会返回空字符串。知道为什么会发生这种情况吗?

嗯,我查看了您的代码并尝试:

var selection = window.getSelection();
var selectionText = selection.anchorNode.textContent
我得到了选定的文本内容

编辑:这似乎是包装在一个点击功能…一秒钟

$('<your selector goes here>').click(function(e) {
  var selection = window.getSelection();
  var range = document.createRange();
  range.selectNodeContents(e.target);
  selection.removeAllRanges();
  selection.addRange(range);
  console.dir(selection.anchorNode.textContent);
  //text content should display...
  //now that the content is highlighted, you can copy it
  document.execCommand('copy');

})
$('')。单击(函数(e){
var selection=window.getSelection();
var range=document.createRange();
范围。选择节点内容(如目标);
selection.removeAllRanges();
选择。添加范围(范围);
console.dir(selection.anchorNode.textContent);
//文本内容应显示。。。
//现在内容已高亮显示,您可以复制它
document.execCommand('copy');
})

我对范围知之甚少,但尝试替换范围。选择NodeContents(元素)带有
范围。选择节点(元素)我重新创建了您的错误,这为我修复了它。示例:
selection.anchorNode.textContent
selection.toString()不同