我正在学习 JavaScript,我想知道为什么会这样:
document.getElementById('partofid'+variable+number)
不起作用?
这是 sample 和 JSfiddle链接,我想要“下一步”按钮删除显示的项目并显示下一个。
HTML:
<div id="div-1"> 1 </div>
<div id="div-2" style="display: none"> 2 </div>
<div id="div-3" style="display: none"> 3 </div>
<div id="div-4" style="display: none"> 4 </div>
<a id="next" href="#">next</a>
JS:
var counter = 1;
var button = document.getElementById('next');
button.addEventListener("click",function(){
var currentDiv = document.getElementById('div-'+counter);
currentDiv.remove();
var nextDiv = document.getElementById('div-'+counter+1);
alert(nextDiv); // why does it return null
alert('div-'+counter+1); // while this doesn't?
nextQuestion.style.display = "block";
counter++;
},true);
最佳答案
尝试使用parseInt
:
var nextDiv = document.getElementById('div-'+parseInt(counter+1,10));
parseInt 函数将其第一个参数转换为字符串,对其进行解析,并返回一个整数。第二个参数是基数,它是数字系统中的“基数”。
关于JavaScript getElementById 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20437244/