网站搜索

html - javascript - 移除元素


我的问题相当基础,但我不明白为什么在下面的代码中,点击按钮时只有按钮消失,而不是整个 div:

<script>
    function remove(id) {
        //get the element node
        element = document.getElementById(id);

        //remove the element from the document
        document.removeChild(element);
    }
</script>

<div id="intro" class="jumbotron">
    <h1>Your Offline Web Dictionary!</h1>
    <p class="lead">

    <div class="controls">
        <input class="span7 " type="text" placeholder=" " name="key">
    </div>
    <div>
        <button class="btn btn-large btn-success" onclick="remove(intro)">
            Dictionary Search
        </button>
    </div>
</div>

JSFiddle

答案#1

问题是按钮元素有一个 remove 属性,所以会调用它而不是你的 remove 函数。还有字符串的那个问题。

<button class="btn btn-large btn-success" onclick="window.remove('intro');console.log(this.remove);">
    Search
</button>

http://jsfiddle.net/HMEVd/76/

答案#2

两个问题。首先,intro 应该是一个字符串,而不是标识符,所以在你的 onclick 中使用 remove('intro')。

其次,document.rwmoveChild 是错误的。removeChild 应该在你移除元素的父元素上调用。常用方法是:

element.parentNode.removeChild(element);