Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
482 views
in Technique[技术] by (71.8m points)

为什么onclick事件点击执行removeChild,第二次点击才生效?

学习时遇到onclick事件点击执行removeChild,第一次点击执行函数,但其中removeChild没有执行,其它代码正常,第二次点击后removeChild才生效。不知为什么,求解

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
    <title>IFE JavaScript Task 04</title>
<style type="text/css">
#list {
    padding: 0;
    margin: 0;
}
#list li {
    margin: 20px 10px;
    float: left;
    list-style: none;
    border:1px solid #e8e8e8;
    background: #eee;
}
</style>
</head>
<body>
<div>
    <button id="leftout">左侧出</button>
    <button id="rightout">右侧出</button>
</div>
<div>
    <ul id="list">
        <li>5</li>
        <li>11</li>
        <li>20</li>
        <li>27</li>
        <li>32</li>
        <li>45</li>
    </ul>
</div>
<script type="text/javascript">

    var leftout = document.getElementById("leftout");
    var rightout = document.getElementById("rightout"); 
    var list = document.getElementById("list");

    leftout.onclick = function() {
        var deleteNode = list.firstChild;
        list.removeChild(deleteNode);
        alert("0");
    }

    rightout.onclick = function() {
        var deleteNode =  list.removeChild(list.lastChild);
    }

</script>
</body>
</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

ul里面第一个孩子节点是空白节点。可以通过判断nodeType取出第一个li,或是使用children[0]都是可以的


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...