javascript - onclick()事件触发的问题

查看:131
本文介绍了javascript - onclick()事件触发的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

</head>
<body>
    <input type="text"  id='input-num'>
    <button type="button" name="button" id="leftin">左侧入</button>
    <button type="button" name="button" id="rightin">右侧入</button>
    <div id="position">
        <span id="none">a</span>
    </div>

    <script type="text/javascript">
        var position = document.getElementById("position");
        var order = document.getElementById("none");
        var input = document.getElementById("input-num");
        var input_num = input.value;
        var leftin = document.getElementById("leftin");
        var rightin = document.getElementById("rightin")

        rightin.onclick = function rightwrap(){
            var input_num = input.value;
            if (input_num%1 === 0) {
                position.innerHTML += "<span>" + input_num + "</span>";
            }
        }

        leftin.onclick = function leftwrap() {
            var input_num = input.value;
            if (input_num%1 === 0){
                var left = document.createElement("span");
                left.textContent = input_num;
                var parent = order.parentNode;
                parent.insertBefore(left, position.firstChild);
            }
        }

    </script>
</body>

两段函数都可以执行,但问题是当我在 Input 中输入数字后点击左侧入按钮,再点击右侧入按钮,再点击左侧入时,就出现以下的提示:

Uncaught TypeError: Cannot read property
'insertBefore' of null at HTMLButtonElement.leftwrap

解决方案

position.innerHTML += "<span>" + input_num + "</span>";

执行了上面那条语句后#position元素下的子元素#none与order变量指向的元素就不是同一个元素了。

因为此时的order指向的元素只是存在于内存中,所以它的parentNode是null,执行下面这条语句的时候就会失败。

parent.insertBefore(left, position.firstChild);

这篇关于javascript - onclick()事件触发的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆