创建和删除< div> javascript中的元素 [英] creating and removing <div> element in javascript

查看:81
本文介绍了创建和删除< div> javascript中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function labelOnClick () {
    function makeDivId(id) {
        return id + "_div";
    };

    var div = this.getElementById(makeDivId(this.id));

    if (div) {
        div.parentNode.removeChild(div);
    } else {
        div = document.createElement("div");
        div.innerHTML = "welcome";
        div.id = makeDivId(this.id);

        this.appendChild(div);
    }
}




<label id="1" onclick="labelOnClick()" > BROWSER </label>
<label id="2" onclick="labelOnClick()"> GAMING CONSOLE </label>

在上面的例子中,我正在尝试创建一个 div 元素,并在再次单击标签时删除创建的 div 元素,但它不起作用。

In the above example, I'm trying to create a div element when a label is clicked and remove the created div element when the label is clicked again, but it's not working.

推荐答案

您的代码中有几个问题:

You have several problems in your code:


  • 在事件处理函数中分配事件处理程序内联( label onclick =...)时将指向全局对象(窗口)。您可以将作为参数传递给函数。

  • When assigning event handlers inline (label onclick="...") inside the event handler function this will point to the global object (window). You can pass this as an argument to the function.

某些浏览器在分配结果时会失败如果没有找到任何元素,则 getElementById()到一个变量(如果我错了,有人会纠正我)。

Certain browsers will fail when assigning the result of getElementById() to a variable if no element is found (someone correct me if I'm wrong).

这样的东西可行:

<script>
function labelOnClick (me) {
    var makeDivId=function (id) {
        return id + "_div";
    };
    var div;

    if (document.getElementById(makeDivId(me.id))) {
        div=document.getElementById(makeDivId(me.id));
        div.parentNode.removeChild(div);
    } else {
        div = document.createElement("div");
        div.innerHTML = "welcome";
        div.id = makeDivId(me.id);

        me.appendChild(div);
    }
}
</script>

<label id="1" onclick="labelOnClick(this)" > BROWSER </label>
<label id="2" onclick="labelOnClick(this)"> GAMING CONSOLE </label>

jsFiddle演示

这篇关于创建和删除&lt; div&gt; javascript中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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