将操作结果显示为选择按钮
Display result of a operation as a choice button
有没有办法将这个操作的结果显示为一个选择按钮?
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>');
请注意,您不能 re-declare 变量 number
,否则您将清除之前存在的值(即用户刚刚 typed-in 的值) .
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!');
}
有没有办法将这个操作的结果显示为一个选择按钮?
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>');
请注意,您不能 re-declare 变量 number
,否则您将清除之前存在的值(即用户刚刚 typed-in 的值) .
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!');
}