Document.exec命令不能按我预期工作

Document.execCommand do not work as I expected

本文关键字:工作 不能按 exec 命令 Document      更新时间:2023-09-26

这是我的表格

<table>
  <tr>
    <th>Name</th>
    <td>Paul Johnson</td>
    <th>Street</th>
    <td>Fake Street</td>
  </tr>
  <tr>
    <th>State</th>
    <td>California</td>
    <th>Car</th>
    <td>Cadillac</td>
  </tr>
</table>

我的脚本由mouseenter事件执行:

$('th').on("mouseenter mouseleave", function(e) {if (e.type === 'mouseenter') {
});

在它里面是这个工具栏,里面有链接对象

toolbar = $("<div />").css({
    "padding": "5px",
    "background" : "#F8F8F8",
    "borderRadius" : "5px 0 5px 5px"
  });
  var link = $("<a />").css({
    "display" : "block",
    "height" : "20px",
    "width" : "20px",
    "marginBottom" : "5px",
    "background-size" : "100%",
    "position" : "relative"})
    .attr({"target" : "_blank"});

我的变量thisNext它获取下一个 td 元素的文本

  var thisNext = $( $(this).next() ).text();

问题为什么我的 var 副本没有复制thisNext值 altrough console.log按预期工作?

编辑 :目标是,如果您单击"复制"附加在名称上的示例对象,则进入剪贴板保罗约翰逊。如果在街上,则复制假街等。

var copy = link.clone().on("click", function (e) {
    e.preventDefault();
    console.log ("thisNext ");
    thisNext.execCommand('copy');
}

工作笔

问题来自以下行:

thisNext.execCommand('copy');

copy命令始终复制选择,因此我们必须首先选择td的内容,然后执行注释,最后重置选择:

var copy = link.clone().on("click", function (e) {
    e.preventDefault();
    var td = e.target.parentNode.parentNode;
    do {
      td = td.nextSibling;
    } while(td && td.nodeType !== 1); // 1 == Node.ELEMENT_NODE
    var range = document.createRange();  
    range.selectNode(td); 
    window.getSelection().addRange(range);
    document.execCommand('copy');   
    // Remove the selections - NOTE: Should use
    // removeRange(range) when it is supported  
    window.getSelection().removeAllRanges();  
})

注意:您可以使用此链接检查您的浏览器是否支持复制命令。

希望这有帮助。