想实现js每点击一次按钮,文本节点数字增加一却出现了NAN,怎么回事?

想实现js每次点击,不断增加一个节点,节点的文本节点的数字比上一个节点的文本节点的数字增加一,但是怎么出现增加为NAN,已经用parseInt将字符串转换为数字了。可能语言描述不清晰,具体的的代码:


<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <title>Document</title>

     <style>

        *{

            margin: 0;

            padding: 0;

        } 

    </style>

</head>

<body>

    <ul class="oUl">

        <li>1</li>

        <li>2</li>

        <li>3</li>

        <li>4</li>

    </ul>

    <input class="oBtn" type="button" value="按钮">

</body>

    <script>

    var oBtn = document.getElementsByTagName("input")[0];

        oBtn.onclick = append;

        function append(){

            var oUl = document.getElementsByTagName("ul")[0];

            var cRlitextnode = parseInt(oUl.lastChild.textNode);

            cRlitextnode++;

            console.log(cRlitextnode);

            var li = document.createElement("li"); 

            var textNode = document.createTextNode(cRlitextnode);

           

            oUl.appendChild(li);

            li.appendChild(textNode);

        }

    </script>

</html>

希望大家能够帮忙解答,谢谢|


繁花如伊
浏览 498回答 2
2回答

米琪卡哇伊

// 1. `Node.textNode`没有这个方法吧???你要获取节点里面的值还是老老实实用`innerHTML`吧~// 2. 假设上面你改好了,然后下面这样的格式写html,用`oUl.lastChild`获取到的....是一个回车符号233,parseInt('') = NaN 。。~惊不惊喜,意不意外~<ul class="oUl">&nbsp; &nbsp; <li>1</li>&nbsp; &nbsp; <li>2</li>&nbsp; &nbsp; <li>3</li>&nbsp; &nbsp; <li>4</li></ul>那么你可以写成这样:// html<ul class="oUl">&nbsp; &nbsp; <li>1</li>&nbsp; &nbsp; <li>2</li>&nbsp; &nbsp; <li>3</li>&nbsp; &nbsp; <li>4</li></ul>&nbsp; // 最后一个不换行// jsvar cRlitextnode = oUl.lastChild.innerHTML;不改html的话——————或者这样var cRlitextnode = oUl.lastElementChild.innerHTML; // 注意firstElementChild的兼容性再或者兼容更好的var cRlitextnode = oUl.children[oUl.children.length - 1].innerHTML;

qq_花开花谢_0

var oBtn = document.getElementsByTagName("input")[0];&nbsp; &nbsp; oBtn.onclick = append;&nbsp; &nbsp; function append(){&nbsp; &nbsp; &nbsp; &nbsp; var oUl = document.getElementsByTagName("ul")[0];&nbsp; &nbsp; &nbsp; &nbsp; var cRlitextnode = parseInt(oUl.lastElementChild.innerText);&nbsp; &nbsp; &nbsp; &nbsp; cRlitextnode++;&nbsp; &nbsp; &nbsp; &nbsp; console.log(cRlitextnode);&nbsp; &nbsp; &nbsp; &nbsp; var li = document.createElement("li");&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; var textNode = document.createTextNode(cRlitextnode);&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; oUl.appendChild(li);&nbsp; &nbsp; &nbsp; &nbsp; li.appendChild(textNode);&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript