js怎么删除可编辑div内的内容

js怎么删除可编辑div内的内容,第1张

首先用选择器获取到div对象
然后就可以重新编写div内容
了,如果里面只有汉字,你可
以直接把内容写成空字符串。
如果里面还有其他节点元素,
同样要获取到元素对象,然后
就可以对他进行 *** 作了

windowonclick = function() {
documentgetElementById('div')parentNoderemoveChild(documentgetElementById('div'));
thisonclick = '';
}
字符串div是你的div的id名

有好几种方式哈;

html代码如下:

<div id="box">
    <div id="inbox">ddddddddddddddddd</div>
</div>
<input type="button" id="remove" value="删除DIV" />

第一种:直接jquery的remove:

  下载个jQuery的文件,然后引入jQuery文件:

    <script type="text/javascript" src="xxxxjqueryjs"></script>
    <script type="text/javascript">
        $("#remove")click(function(){
            $("#inbox")remove();
                        //或者
                        $("box")remove("#inbox");
        });
    </script>

第二种:用JS的innerHTML

    <script type="text/javascript">
        function g(id) {
            return documentgetElementById(id);
        }
        g("remove")onclick = functioin(){
            g("box")innerHTML = '';
        }
    </script>

第三种:用JS的outerHTML

    <script type="text/javascript">
        function g(id) {
            return documentgetElementById(id);
        }
        g("remove")onclick = functioin(){
            g("inbox")outerHTML = '';
        }
    </script>

第四种:用JS的removeChild

    <script type="text/javascript">
        function g(id) {
            return documentgetElementById(id);
        }
        g("remove")onclick = functioin(){
            g("box")removeChild(g("inbox"));
        }
    </script>

其他还有,就不列举了

测试过的,还有我说了给按钮加ID,不知道你加了没,下面是我的测试代码:
<body>
<div>
<div>
<input type="text" id="items" value="请输入">
<input id="id1" type="button" onclick="cls(this)" value="del" />
</div>
<div>
<input type="text" id="items" value="请输入">
<input id="id2" type="button" onclick="cls(this)" value="del" />
</div>
<br>
<input id="id3" type="button" onclick="cls(this)" value="del" />
</div>
<script>
function cls(obj) {
var ob = documentgetElementById(obj);
obparentNodeparentNoderemoveChild(obparentNode);
}
function del() {
alert('删除前');
cls('id1');
cls('id2');
cls('id3');
alert('删除完毕');
}
windowonload = del();
</script>
</body>

将div的innerHTML置为空即可,下面有2类方法可以实现:

假设有如下的html片段:

<div id="test">这是要删除的内容,还要保留test本身</div>

原生js法

documentgetElementById('test')innerHTML = '';

jQuery法

$('#test')empty();//jQuery方法一
$('#test')html('');//jQuery方法二

jquery:

$("div")remove();

javaScript:

var arrayOfDiv = documentgetElementsByTagName("div");
var parent = arrayOfDiv[0]parentNode;
var length = arrayOfDivlength;
for(var i=0;i<length;i++)    
  {  
     parentremoveChild(arrayOfDiv[0]); 
  }

如果你页面上还有其它div,你只想删除新添加的,那最好是在新添加的时候将div放入一个数组,删除的时候删除这个数组中的div就可以了


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/12894788.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-28
下一篇 2023-05-28

发表评论

登录后才能评论

评论列表(0条)

保存