li从上到下顺序点击可正常插入span,从下往上点击会报错,请教各位帮忙查看问题在哪里?

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>test</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        ul li {
            width: 300px;
            height: 20px;
            border: 1px solid #663333;
            margin-bottom: 5px;
        }

    </style>

</head>
<body>
<ul>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
</ul>


<script>
    window.onload = function () {
        var ul_li = document.getElementsByTagName('li');

            for (var i = 0; i < ul_li.length; i++) {
                ul_li[i].index = i;
                ul_li[i].onclick = function () {
                    if (!this.getAttribute('index')) {
                        this.setAttribute('index', this.index);
                        var new_div = document.createElement('span');
                        var new_span_text = document.createTextNode('hello');
                        new_div.className = 'span_class';
                        new_div.appendChild(new_span_text);
                        ul_li[this.index].appendChild(new_div);
                    }
                    var t_lenght = document.getElementsByClassName('span_class');
                    for (var j = 0; j < t_lenght.length; j++) {
                        t_lenght[j].index = j;
                        t_lenght[j].style.display = 'none';
                    }
                    //debugger;
                    t_lenght[this.index].style.display = 'block';
                    console.log(t_lenght[this.index].index);
                }
            }
 }
</script>
</body>
</html>
youngfever
浏览 1256回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript