如何使用 Jquery/JavaScript 完全删除画布元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15598360/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:21:02  来源:igfitidea点击:

How to completely remove the canvas element with Jquery/JavaScript?

javascriptjqueryhtml5-canvas

提问by klewis

I have a canvas object that loads on my page dynamically from a jQuery plugin. It has no wrapper, no id or class associated to it. But I need to remove it after

我有一个从 jQuery 插件动态加载到我的页面上的画布对象。它没有包装器,没有与之关联的 id 或类。但我需要在之后删除它

$(window).resize(function)() {...} 

takes place. I have tried using jQuery's

发生。我试过使用 jQuery 的

...next().remove(); 

technique, so that the neighboring div element can remove it from the DOM, but I am getting issues. specifically, additional elements on my page are also getting removed. Is there a healthy way to about this?

技术,以便相邻的 div 元素可以从 DOM 中删除它,但我遇到了问题。具体来说,我页面上的其他元素也被删除了。有没有一种健康的方法来解决这个问题?

Thanks!

谢谢!

回答by KryptoniteDove

If you are not using multiple canvas elements, simply

如果您没有使用多个画布元素,只需

$('canvas').remove();

Will remove all matched elements on the page. http://jsfiddle.net/vj6NP/

将删除页面上所有匹配的元素。http://jsfiddle.net/vj6NP/

If you do have multiple canvas on the page and would like to remove only one, you could select which one to remove using nth-of-type.

如果页面上确实有多个画布并且只想删除一个,则可以使用nth-of-type选择要删除的一个。

For example to remove the first instance http://jsfiddle.net/vj6NP/3/: -

例如删除第一个实例http://jsfiddle.net/vj6NP/3/: -

$('canvas:nth-of-type(1)').remove();

回答by Dogoferis

How many canvas elements do you have on the page? If there is only one; and you don't plan to ever add any in the future it might be simplest just to do

页面上有多少个画布元素?如果只有一个;并且您不打算在将来添加任何内容,这可能是最简单的做法

var dynamic_canvas = $('canvas');
if(dynamic_canvas) dynamic_canvas.remove();

回答by pasx

The easiest way is to keep a reference to the canvas element added to the document then remove it using JQuery:

最简单的方法是保留对添加到文档的 canvas 元素的引用,然后使用 JQuery 将其删除:

this.canvas = document.createElement('canvas');
//later...
$(this.canvas).remove();