我有一个正在进行的项目,我需要根据输入字段中输入的数字绘制一些HTML画布(从1到10)。
或许更简单的方法是在绘制之前已经在DOM中创建了画布,但是此函数中的所有内容都需要动态发生,因此需要使用JavaScript函数绘制画布本身。我用switch语句取得了更好的进展,但我觉得for循环会更合适。
由于某种原因,小提琴不能正常工作,但该按钮在我的Cloud9环境中绘制了一个画布。现在我只需要绘制一些与输入值相对应的画布。
JS小提琴:https://jsfiddle.net/m4hys8tr/
HTML:
<form action='#' method='get' name=queueform id=queue>
<div id='queueblock'>
<div class='formblock'>
<div class='row'>
<div class='cell'>
<strong>Quantity:</strong><br>
<hr>
<label for='items'>Items:</label>
<input id='quantity' size='2' type='text'><br><br>
<strong><p>Enter a maximum of 10 items</p></strong>
</div>
<div class='cell'><br><br>
<div>
<button onclick='drawCanvas()' id='getitemsbutton' class='button' type='button'>Get Items</button>
<button id='clearbutton' class='button' type='reset'>Clear</button>
<button id='queuebutton' class='button' type='submit'>Send to Queue</button>
</div>
</div>
JS:
function drawCanvas() {
var canvasBlock = document.getElementById('canvasblock');
var canvas = document.createElement('canvas');
var quantity = document.queueform.quantity.value;
canvas.id = 'canvas01', 'canvas02', 'canvas03', 'canvas04',
'canvas05', 'canvas06', 'canvas07', 'canvas08',
'canvas09', 'canvas010';
canvas.width = 70;
canvas.height = 70;
canvas.style.border = '1px solid';
for (var i = 0; i < quantity; i++) {
canvasBlock.appendChild(canvas);
}
var c1 = document.getElementById('canvas01');
console.log(c1);
}
答案 0 :(得分:0)
function drawCanvas() {
var canvasBlock = document.getElementById('canvasblock');
var quantity = document.queueform.quantity.value;
for (var i = 0; i < quantity; i++) {
var canvas = document.createElement('canvas');
canvas.id = 'canvas'+('0' + i).slice(-2) // generate name dynamically. ('0' + i).slice(-2) is a trick to add a zero if the current number is < 10
canvas.width = 70;
canvas.height = 70;
canvas.style.border = '1px solid';
canvasBlock.appendChild(canvas);
}
var c1 = document.getElementById('canvas01');
console.log(c1);
}
&#13;
<div id='canvasblock'>
</div>
<form action='#' method='get' name=queueform id=queue>
<div id='queueblock'>
<div class='formblock'>
<div class='row'>
<div class='cell'>
<strong>Quantity:</strong><br>
<hr>
<label for='items'>Items:</label>
<input id='quantity' size='2' type='text'><br><br>
<strong><p>Enter a maximum of 10 items</p></strong>
</div>
<div class='cell'><br><br>
<div>
<button onclick='drawCanvas()' id='getitemsbutton' class='button' type='button'>Get Items</button>
<button id='clearbutton' class='button' type='reset'>Clear</button>
<button id='queuebutton' class='button' type='submit'>Send to Queue</button>
</div>
</div>
&#13;