隐藏和删除DOM元素

隐藏和删除DOM元素

本文介绍了隐藏和删除DOM元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

处理DOM元素,隐藏或删除的最佳方法是什么?假设环境可以改变几次。元素可以包含点击回调或其他事件回调。

What is the best way to handle DOM elements, hide or delete?. assume that the environment can change several times. Elements can have click-callbacks or other event callback.

隐藏

隐藏什么是最好的?如果点击按钮隐藏多个项目,您可以逐一隐藏,也可以创建css规则来执行此操作。

When hide what is best?. If clicking a button hide multiple items, you can hide one by one or you can also create css rules to do so.

选项1:

<style>
.superContent{/*...*/}

.superContent.noEdit .occultable{
    display:none;
}
</style>

<form class="superContent" action="...">
    <label>Name</label>
    <input type="text" />
    <input type="submit" class="occultable" value="send"/>
</form>

<button id="hideAll">Edit</button>
<script type="text/javascript">
    $("#hideAll").click(function(){
        $(".superContent").toggleClass("noEdit");
    });
</script>

另一个选项是只隐藏所需的项目(这些项目可能有几个或很多):

The other option is to just hide the desired items (these may be few or many):

选项2:

<script type="text/javascript">
    $("#hideAll").click(function(){
        $(".occultable").toggle();
    });
</script>

删除

要修改DOM,您还可以删除不需要的项目,稍后重新插入。

To modify the DOM you can also delete unwanted items and re-insert them later.

选项3:

<form class="superContent">
    <label>Name</label>
    <input type="text" />
    <input id="sendbutton" type="submit" class="occultable" value="send"/>
</form>

<button id="hideAll">Edit</button>​

<script type="text/javascript">
$("#hideAll").click(function(){
    if( $(".superContent").find("#sendbutton").length>0 ){
        $(".superContent").find("#sendbutton").remove();
    }
    else{
        $(".superContent").append('<input id="sendbutton" type="submit" class="occultable" value="send"/>');
    }
});​
</script>

这些只是小例子。假设一个UI包含大量的元素。你认为最好的选择是什么?其中有更少的内存泄漏和更多的性能?

These are just small examples. Assuming a UI that contains a large number of elements. What do you think the best option?. Which has less memory leak and more performance?

有一些javascript框架,如kendo-ui删除元素。
jQueryUI喜欢隐藏项目,但是小部件Tab sortable创建了用户临时拖动的选项卡。

There are some javascript frameworks like kendo-ui that removes elements.jQueryUI prefers to hide items, but the widget Tab sortable creates the tab temporarily dragged by the user.

推荐答案


  • 当您想要重新显示元素时,隐藏是最好的。

  • 当您不需要再次使用元素时,移除是最好的。

当你隐藏元素然后重新显示它们时,这些元素不会丢失所有的回调和数据,特别是当jQuery在使用时。

When you hide elements and then re-show them those elements don't lose all their callback and data, specially when jQuery is in use.

当你删除不必要的元素,你减少为你的页面分配的内存,虽然在大多数情况下它不会是一个重大的变化。

When you remove unnecessary elements, you reduce the memory allocated for your page, though in most scenarios it won't be a significant change.

这篇关于隐藏和删除DOM元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 21:05