使用append方法在剪贴板上进行JavaScript For Loop迭代

时间:2018-12-18 16:26:08

标签: javascript jquery for-loop

当我使用append方法创建新的div时,循环中的某些内容导致剪贴板内容的增量迭代被粘贴到.editable div中。

Fiddle here单击“创建新的div”按钮4或5次,然后粘贴到框中,然后查看问题。

堆栈片段:

$("button").click(function () {
        $(".body").append("<div class=\"editable\" style=\"border:1px solid red\" contenteditable></div><br />")
        myFunction();
    })

    $(".editable").on("paste", function() {
        myFunction();
    })

    function myFunction() {
            var editors = $(".editable");
        for (var i = 0, l = editors.length; i < l; i++) {
            editors[i].addEventListener("paste", function (e) {
                e.preventDefault();
                var text = e.clipboardData.getData("text/plain");
                document.execCommand("insertHTML", false, text);
            });
        }
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<div style="color:blue"><span style="font-size:2em">HTML</span></div>

<button>
  Create new div
</button>

<div class="body">

  <div class="editable" style="border:1px solid red" contenteditable></div><br />
  <div class="editable" style="border:1px solid red" contenteditable></div><br />
  
</div>

1 个答案:

答案 0 :(得分:2)

这是怎么找你的?

// When something has been pasted to an editable element. 
const onPaste = (e) => {
  e.preventDefault();
  const text = e.clipboardData.getData("text/plain");
  document.execCommand("insertHTML", false, text);
};


// Add some new editable element to the DOM.
const buttonClickHandler = () =>  {
  const template = "<div class=\"editable\" " + 
    " style=\"border:1px solid red\" contenteditable></div><br/>";
  $(".body").append(template);
  onAppend();
};


// Simply iterate over an array and add a past event listener.
const manager = a => a.forEach(i => i.addEventListener("paste", e => onPaste(e)));


// Fire this method when a new editable item has been added to the DOM.
const onAppend = () => {
  const list = document.querySelectorAll(".editable");
  manager([list[list.length - 1]]);
};


// On load. 
$(document).ready(() => {
  $("button").click(buttonClickHandler);
  manager(document.querySelectorAll(".editable"));
});
div[contenteditable] {
  height: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="color:blue"><span style="font-size:2em">HTML</span></div>

<button>
  Create new div
</button>

<div class="body">

  <div class="editable" style="border:1px solid red" contenteditable></div><br />
  <div class="editable" style="border:1px solid red" contenteditable></div><br />

</div>