我试图在单击按钮时删除 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 也变得更简单。
关于javascript - 单击按钮删除div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31104154/