为什么选择范围和弹出窗口不能在javascript中一起工作

why select range and popup window can not work together in javascript?

本文关键字:javascript 一起 工作 不能 窗口 范围 选择 为什么      更新时间:2023-09-26

我使用这个html结构来弹出一个新窗口,并选择预标记中的所有内容:

<a href="#" onclick="popup(this)">Open Ppup</a> 
<a class="selectable" href='javascript:fnSelect("a1")'>[Select All Code]</a>
<pre class="CodeBlock linenums" id="a1">
line 1<br />
line 2<br />
line 3
</pre>
<a href="#" onclick="popup(this)">Open Popup</a> 
<a class="selectable" href='javascript:fnSelect("a2")'>[Select All Code]</a>
<pre class="CodeBlock linenums" id="a2">
 line 4<br />
 line 5<br />
 line 6
 </pre>

弹出窗口的js:

function popup(obj)
{
var myHtml = '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8">   <title>Popup</title></head><body>' +
  $(obj).next('.CodeBlock').html() +
  '</body></html>';
  var generator = window.open('','name','height=400,width=500');
  generator.document.body.innerHTML = myHtml;
}

以及用于选择的js:

function fnSelect(objId) {
    fnDeSelect();
    if (document.selection) {
    var range = document.body.createTextRange();
        range.moveToElementText(document.getElementById(objId));
    range.select();
    }
    else if (window.getSelection) {
    var range = document.createRange();
    range.selectNode(document.getElementById(objId));
    window.getSelection().addRange(range);
    }
}
function fnDeSelect() {
    if (document.selection) document.selection.empty(); 
    else if (window.getSelection)
            window.getSelection().removeAllRanges();
}

似乎两个锚点在html中不能在一起。如果放在一起,弹出窗口就不再工作了(至少它给了我未定义的作为内容)。如果我用[Select All Code]跳过锚点,弹出窗口工作正常。看看这把小提琴:http://jsfiddle.net/Ax8Hz/47/

我的问题是:当另一个锚点(SelectAllCode)也在html中时,为什么弹出窗口不再工作?如何解决此问题?

试试这个:

function popup(obj)
{
  var myHtml = '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Popup</title></head><body>' +
      $(obj).nextAll('.CodeBlock').first().html() +
      '</body></html>';
  var generator = window.open('','name','height=400,width=500');
  generator.document.body.innerHTML = myHtml;
}

.next()查看下一个元素,而不是该类的下一个元件,因此使用nextAllfirst()本质上做相同的事情