我正在创建一个允许用户输入数字 1 - 128 的 jQuery 程序,输入的数字动态创建一个包含等于用户输入数字的正方形的网格(例如,12 将创建 12 列和行)。
我选择使用 sweetAlerts 而不是常规提示来询问用户输入。当用户输入数值时,网格会动态创建,但我的 colorRandomizer() 函数不再起作用。
colorRandomizer(); 当用户将鼠标悬停在正方形上时,随机化网格正方形的背景颜色。当我使用常规提示时,colorRandomizer() 函数可以完美运行,但是使用 sweetAlerts 会出现网格,但我的 colorRandomizer() 不起作用。
我已将代码放在下面可能出现问题的地方。
调用触发按钮:
//random option button click function
$('#option-random').on('click', function () {
//calls swal (sweetAlert)
test();
// calls colorRandomizer function to give squares random colors on hover
colorRandomizer();
});
sweetAlerts 的功能:
function test() {
swal({
title: "Hello!",
text: "Enter a number between 1-128 for squares in your grid",
type: "input",
showCancelButton: true,
showConfirmButton: true,
closeOnConfirm: false,
animation: "slide-from-top",
inputPlaceholder: "e.g 12"
}, function (squares) {
if (squares >= 1 || squares <= 128) {
// calls build function to build the grid-table
buildGrid(squares);
} else {
swal("Oops! You didn't enter a number between 1-128");
}
});
}
随机背景颜色的功能(这是停止工作的功能):
function colorRandomizer() {
$('.grid_squares').on('mouseover', function () {
var color1, color2, color3;
color1 = (Math.floor(Math.random() * 256));
color2 = (Math.floor(Math.random() * 256));
color3 = (Math.floor(Math.random() * 256));
$(this).css({
"background-color": "rgb(" + color1 + "," + color2 + "," + color3 + ")"
});
});
}; //colorRandomizer
这是构建网格/正方形的功能,此功能有效,但也许我忽略了导致问题的原因:
// create grid-table
function buildGrid(squares) {
// assigns square_size to the width of the grid-table and divides it by the squares input from user and - 2 for the squares border size
var square_size = $('#grid-table').width() / squares - 2;
// while counter "i" is less or equal to squares user input create div with class .gride_squares and append newly created div to grid-table
for (var i = 1; i <= squares; i++) {
for (var j = 1; j <= squares; j++) {
$('#grid-table').append('<div class="grid_squares"></div>');
}
// while counter "j" is less or equal to squares user input create div with class .rows and append newly created div to grid-table; .rows is used to clear the floated .grid_squares in my external css
$('#grid-table').append('<div class="rows"></div>');
}
// assigns width and height css values to .grid_squares
$('.grid_squares').css({
'width': square_size,
'height': square_size
});
}; // buildGrid