有没有办法将此操作的结果显示为选择按钮?
var number = prompt("Enter a random number");
var number = number % 4;
这是你要找的吗?
var number = prompt("Enter a random number");
number = number % 4;
$('body').append('<button>' +number+ '</button>');
请注意,您不得重新声明变量 number
,否则您将清除之前存在的值(即用户刚刚输入的值(。
var number = prompt("Enter a random number");
number = number % 4;
$('body').append('<button>' +number+ '</button>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
如果这是您要实现的目标,您可以执行以下操作:
makeButton();
function makeButton() {
var number = prompt("Enter a random number");
var btnEl;
if (number) {
if (isNaN(number)) {
console.log('The input is not a number');
return;
}
number = number % 4;
btnEl = document.createElement('input');
btnEl.setAttribute('type', 'button');
btnEl.setAttribute('value', number);
btnEl.addEventListener('click', () => {
console.log(`This buttons value is: ${number}`);
});
document.querySelector('body').appendChild(btnEl);
return;
}
console.log('A value is required!');
}