我正在建造一个河内解决方案塔。当用户点击带有数字的按钮时,我试图使块消失,即。当页面加载时有10个块,但是当用户点击8按钮时,我希望删除两个最大的块。
HTML:
<div class="pillon-1">
<div id="percent-100"></div><!--
--><div id="percent-90"></div><!--
--><div id="percent-80"></div><!--
--><div id="percent-70"></div><!--
--><div id="percent-60"></div><!--
--><div id="percent-50"></div><!--
--><div id="percent-40"></div><!--
--><div id="percent-30"></div><!--
--><div id="percent-20"></div><!--
--><div id="percent-10"></div>
</div>
按钮的标记:
<button name="button" type="submit" id="btn-8" onclick="eightBlocks();">8</button>
我到目前为止的JS,但无法使其发挥作用:
function eightBlocks() {
const el = document.getElementsByClassName('pillon-1')[0, 1];
el.removeChild(document.getElementById('percent-100 percent-90'));
return false;
}
非常感谢任何帮助。
答案 0 :(得分:1)
removeThisAfterTesting();
function removeThisAfterTesting(){
var els = document.querySelectorAll("*[id^='percent-']");
els.forEach(function(el){
el.innerHTML = el.id;
})
}
function eightBlocks() {
document.getElementById('percent-90').remove();
document.getElementById('percent-100').remove();
return false;
}
Element.prototype.remove = function() {
this.parentElement.removeChild(this);
}
&#13;
<div class="pillon-1">
<div id="percent-100"></div><!--
--><div id="percent-90"></div><!--
--><div id="percent-80"></div><!--
--><div id="percent-70"></div><!--
--><div id="percent-60"></div><!--
--><div id="percent-50"></div><!--
--><div id="percent-40"></div><!--
--><div id="percent-30"></div><!--
--><div id="percent-20"></div><!--
--><div id="percent-10"></div>
</div>
<button name="button" type="submit" id="btn-8" onclick="eightBlocks();">8</button>
&#13;
答案 1 :(得分:0)
function eightBlocks() {
var $container = document.querySelector('.pillon-1')
var $removable1 = document.querySelector('.pillon-1 #percent-100')
var $removable2 = document.querySelector('.pillon-1 #percent-90')
if ($removable1) $container.removeChild($removable1)
if ($removable2) $container.removeChild($removable2)
}
&#13;
.pillon-1 {
display: flex;
flex-direction: column;
}
.pillon-1 div {
width: 200px;
height: 40px;
background-color: red;
border: 1px solid white;
}
&#13;
<div class="pillon-1">
<div id="percent-100">100</div><!--
--><div id="percent-90">90</div><!--
--><div id="percent-80">80</div><!--
--><div id="percent-70">70</div><!--
--><div id="percent-60">60</div><!--
--><div id="percent-50">50</div><!--
--><div id="percent-40">40</div><!--
--><div id="percent-30">30</div><!--
--><div id="percent-20">20</div><!--
--><div id="percent-10">10</div>
</div>
<button name="button" type="submit" id="btn-8" onclick="eightBlocks();">8</button>
&#13;