javascript - 单击按钮删除div

标签 javascript jquery html

我试图在单击按钮时删除 div 但问题是我需要按钮删除它包含的 div 而不将 div 的 id 传递给删除按钮

所以最后这段代码应该能够删除 div 而无需传递 div 的 id 而不是它取决于传递 this 引用

<!doctype html>
<html>

<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script>
        $(document).ready(function() {
            $(document).on('mouseenter', '#divbutton', function() {
                $(this).find(":button").show();
            }).on('mouseleave', '#divbutton', function() {
                $(this).find(":button").hide();
            });
        });
    </script>

    <style>
        #divbutton {
            height: 100px;
            background: #0000ff;
        }

        #divbutton2 {
            height: 100px;
            background: #0000ff;
        }

        #divbutton3 {
            height: 100px;
            background: #0000ff;
        }
    </style>
</head>
<body>
    <div id="divbutton">
        <button type="button" style="display: none;" id="i" onclick="document.body.removeChild(document.getElementById('divbutton'))">Hello</button>
    </div>

    <div id="divbutton2">
        <button type="button" style="display: none;" id="i" onclick="document.body.removeChild(document.getElementById('divbutton2'))">Hello </button>
    </div>

    <div id="divbutton3">
        <button type="button" style="display: none;" id="i" onclick="document.body.removeChild(document.getElementById('divbutton3'))">Hello </button>
    </div>
</body>

</html>

最佳答案

如果您想知道如何使用this 引用获取父元素并将其传递给removeChild,那么很简单,只需使用parentNode。 :

<div class="divbutton">
    <button type="button" style="display: none;" id="i" onclick="document.body.removeChild(this.parentNode)">Hello</button>
</div>

但是,由于您使用的是 jQuery,因此利用它的强大功能是有意义的:

$(document).on('mouseenter', '.divbutton', function () {
    $(this).find(":button").show();
}).on('mouseleave', '.divbutton', function () {
    $(this).find(":button").hide();
}).on('click', ':button', function() {
    $(this).parent().remove();
});

我还将 ids #divbuttonX 更改为类名 .divbutton,在这种情况下 CSS 也变得更简单。

演示: http://jsfiddle.net/5qfjo0c7/

关于javascript - 单击按钮删除div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31104154/

相关文章:

javascript - JQuery .blur() 不工作

javascript - AJAX 调用正在向 Controller 操作发送空数据

JavaScript - 以及创建和使用 Java 对象

jquery - 如何从下拉列表中删除所选项目(使用 Jquery)

html - html5样板的基本样式

html - 两个跨度,一个左对齐,一个右对齐,两个底部对齐

html - Making 'file' input element mandatory(必需)

javascript - 如何添加事件选择器

javascript - 使用Javascript获取IE的浏览器版本

JavaScript onClick函数触发ActionsScript3事件