粘贴或删除某些内容后,如何从DOM中取出元素? [英] How can I take elements out of the DOM, after pasting or dropping something?

查看:70
本文介绍了粘贴或删除某些内容后,如何从DOM中取出元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery的remove()函数删除粘贴在contenteditable区域中的所有内容(文本除外).我对禁用图像特别感兴趣.

I am using jQuery's remove() function to delete everything that is pasted/dropped in a contenteditable area, except for text. I am especially interested in disabling images.

我尝试过通过这种方式

function removeImg() {
  setInterval(function() {
    $("#editableDiv").contents(":not(p)").remove();
  }, 1);
}

#editableDiv {
  padding-left: 10px;
  width: 100%;
  border: solid 1px blue;
}

img {
  width: 100px;
  margin-right: 20px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="editableDiv" contenteditable onpaste="removeImg();" ondrop="removeImg();">
  <p>Images that you paste or drop here should be automatically removed.</p>
</div>
<hr>
<p>You can use these images:</p>
<img src="https://i7.pngguru.com/preview/134/138/533/star-golden-stars.jpg">
<img src="https://i7.pngguru.com/preview/134/138/533/star-golden-stars.jpg">
<p>Either copying-pasting or dragging-dropping them don't work...</p>

但是,它不起作用,我也不明白为什么.控制台未显示任何错误.我在Firefox和Chrome的最新版本上都尝试过.

However, it is not working, and I do not understand why. The console shows no errors. I tried it on both Firefox and Chrome's latest versions.

有人可以帮我吗?

推荐答案

没有一个答案为我要实现的目标提供了解决方案.最终通过更改此方法对其进行了修复:

None of the answers provided a solution to what I was trying to achieve. Ended up fixing it by changing this:

function removeImg() {
  setInterval(function() {
    $("#editableDiv").contents(":not(p)").remove();
  }, 1);
}

对此:

function removeImg() {
  setTimeout(function() {
    $('#editableDiv :not(p)').remove();
  }, 1);
}

这篇关于粘贴或删除某些内容后,如何从DOM中取出元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆