javascript - 克隆/复制 DOM 元素功能无法正常工作

标签 javascript jquery angular

My question is different than this because that code is not working on clicking the clone button, i have explained how that code is working with the help of an video. I am not getting any response on that thread so after waiting for 3 days, i am posting this question for further help.

我有一个非常基本的要求。当我右键单击一个元素时,它会显示一个上下文菜单,该菜单有一个“克隆”按钮。我想要的是,当单击此按钮时,它应该克隆或复制此选定元素旁边的相同元素。

我面临的问题,当我右键单击>我得到菜单>当我单击克隆时我的函数将不会返回值,如果我再次右键单击它将返回值,其次我无法将其附加到所选文本下方,下面是我的代码:

我的editpage.ts代码,使用的函数是clone()

//for clone
  clone(){
    console.log("clone function here");
  document.addEventListener("contextmenu", (e) => {
  e.preventDefault();
  console.log(e, e.srcElement.outerHTML);
  this.htmlstring = e.srcElement.outerHTML;
});
  }

  // code for right click context menu
  rightPanelStyle: Object = {};

  detectRightMouseClick($event) {
    // disabling the default browser window which comes on right click
    document.addEventListener('contextmenu', event => event.preventDefault());

       if($event.which === 3) {
           this.rightPanelStyle = {'display':'block','left':$event.clientX + 'px','top':$event.clientY + 'px'};
            return false;
       }
  }

Below showing a small 20 second video of what exactly is happening - http://youtu.be/I4nAb77lk_Q?hd=1

请帮忙

最佳答案

您可以使用“cloneNode(true)”函数来克隆元素。传递给函数的参数表示克隆元素及其子节点。

document.addEventListener('contextmenu', function(e) {
  var targetElement = e.target;
  clone = targetElement.cloneNode(true);
  targetElement.appendChild(clone);
})

在您的代码中,在clone()函数内附加“contextmenu”事件。如果您在启动代码时调用它,那就太好了。如果没有,我建议在启动代码时执行此操作。否则,上下文菜单事件将在您调用克隆函数后附加。

希望这有帮助。

关于javascript - 克隆/复制 DOM 元素功能无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44669479/

相关文章:

javascript - 以 Angular 添加 AsyncValidator 时出错

javascript - Router.navigate 没有加载 Angular 中的完整页面内容

angular - 关闭后启动对话框未打开

php - 如何在javascript中嵌入php脚本?

javascript - 使用 TableSorter Pager (JQuery) 的错误分页

javascript - Grails 中具有一个域类的依赖下拉菜单

javascript - jQuery 的 "uploadProgress"未在 "$.ajax"中触发

javascript - 具有重复条目的数组问题

javascript - 图像随页面滚动

javascript - parallax.js parallax-slider 视差内容和图像