我用按钮填充了数组(使用 document.create("input"))。我想将它们打印到屏幕上,但我无法获取元素 mainArr[i][j]。当我 console.log() 它时,打印未定义但在范围之外它给出了我的预期。我试过这个:
for (var i = 0; i < mainArr.length; i++) {
var p = document.createElement('P');
for (var j = 0; j < mainArr[i].length; j++) {
element = mainArr[i][j];
p.appendChild(element);
}
$('#keyPad').append(p);
}
我期望这样的输出:
<p>
<input type="button" class="sil" value="C" style="width:50px">
<input type="button" class="hepsiniSil" value="AC" style="width:50px">
</p>
<p>
<input type="button" class="buttons" value="7">
<input type="button" class="buttons" value="8">
<input type="button" class="buttons" value="9">
<input type="button" class="buttons" value="*" >
</p>
<p>
<input type="button" class="buttons" value="4">
<input type="button" class="buttons" value="5">
<input type="button" class="buttons" value="6">
<input type="button" class="buttons" value="-">
</p>
<p>
<input type="button" class="buttons" value="1">
<input type="button" class="buttons" value="2">
<input type="button" class="buttons" value="3">
<input type="button" class="buttons" value="+">
</p>
<p>
<input type="button" class="buttons" value="0">
<input type="button" value="=" style="width:50px" onclick='esittir()'>
<input type="button" class="buttons" value="/">
</p>
下面是这样的:
$(document).ready(function () {
var butArr = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '+', '-', '*', '/', '=', 'C', "AC"];
var mainArr = [];
$('.createBut').click(function () {
var but = document.createElement("input");
var butClass = $('#inputClass').val();
var butValue = $('#inputValue').val();
var butRow = $('#inputRow').val();
var butColumn = $('#inputColumn').val();
var butWidth = $('#inputWidth').val();
var butHeigth = $('#inputHeigth').val();
var butClick = $('#inputClick').val();
but.type = 'button';
but.value = butValue;
but.className = butClass;
but.style.width = butWidth;
but.style.height = butHeigth;
//but.onclick = butClick;
for (var i = 0; i < 17; i++) {
mainArr[butRow] = [];
for (var j = 0; j < 17; j++) {
mainArr[butRow][butColumn] = but;
}
}
});
最佳答案
您的代码有误 - 您使用:
mainArr[butRow][butColumn] = but;
butRow
和 butColumn
没有改变
这应该可以解决您的问题:
for (var i = 0; i < 17; i++) {
mainArr[i] = [];
for (var j = 0; j < 17; j++) {
var but = document.createElement("input");
but.type = 'button';
but.value = butValue;
but.className = butClass;
but.style.width = butWidth;
but.style.height = butHeigth;
mainArr[i][j] = but;
}
}
关于javascript - 如何从 Javascript 中的多维数组中获取元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40609765/