单击按钮后的无响应元素

Unresponsive elements after button click

本文关键字:响应 元素 按钮 单击      更新时间:2023-09-26

背景:

前几天我启动了Javascript,并构建了这个草稿板:

http://frankpeelen.github.io/sketch-pad/

以下是关于的说明

http://www.theodinproject.com/web-development-101/javascript-and-jquery

问题:

它基本上完成了,除了使用"新建"按钮创建新网格外,其他操作都很好。突然之间,"方块"停止了对"悬停"事件的响应。我已经搜索过了,但找不到任何类似的问题。有什么想法吗?

代码:

$(document).ready(function() {
	var build = function(h, w) {
		var height = h;
		var width = w;
		//Loop through height to create rows
		for (i = 1; i <= height; i++) {
			$("#sketchpadcontainer").append("<div class='row'></div>");
			//Loop through width to create divs in each row
			for (j = 1; j <= width; j++) {
	    		$(".row:last-child").append("<div class='sqrcontainer'><div class='square'></div></div>");
	    	}
		}
	};
	//Build default 16x16 grid
	build(16, 16);
	$("button").click(function() {
		var size = parseInt(prompt("How many squares per side would you like? Please enter a number."));
		//In case the number entered > 50
		if (size > 50) {
			$(".row").remove();
			build(50, 50);
			alert("The number you entered was too large. The number 50 has been used instead.")
		}
		//In case a non-number is entered
		else if (isNaN(size)) {
			$(".row").remove();
			build(16, 16);
			alert("You didn't enter a number. The default of 16 has been used.")
		}
		//In case a number <= 50 is entered
		else {
			$(".row").remove();
			build(size, size);
		}
	})
	$(".square").hover(
	//Mouse in
	function () {
		$(this).css("background-color", "blue");
	},
	//Mouse out
	function () {} );
});
html, body, #sitecontainer {
	height: 100%;
	width: 100%;
	margin: 0px;
}
#sketchpadcontainer {
}
button {
	display: block;
	margin: 0 auto;
	margin-top: 2em;
	margin-bottom: 1em;
}
#sketchpadcontainer {
}
.row {
	text-align: center;
}
.sqrcontainer {
	height: 1.5em;
	width: 1.5em;
	display: inline-block;
}
.square {
	width: 1em;
	height: 1em;
	margin: .1em;
	border-color: black;
	border-style: solid;
	border-radius: .1em;
}
<!DOCTYPE html>
<head>
	<title>Sketch Pad</title>
	<link rel="stylesheet" type="text/css" href="css/style.css">
	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
	<script type='text/javascript' src="js/javascript.js"></script>
	<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
	<div id="sitecontainer">
		<div id="buttoncontainer">
			<button type="button">New</button>
		</div>
		<div id="sketchpadcontainer">
		</div>
	</div>
</body>

您正在删除构建方法之前的div。这意味着悬停侦听器将被删除到。您必须再次将它们添加到.square元素中。

只需移动

$(".square").hover(
//Mouse in
function () {
    $(this).css("background-color", "blue");
},
//Mouse out
function () {} );

在您的构建方法内部

更改$(".square").hover(

$(document).on("hover" ,".square", function(){ . . . })$(".square").hover(中的Ur问题-在$(document).ready之后工作,但在u添加新行之后-文档就绪不触发,并且Ur元素没有事件,并且触发。在页面上的每个元素上工作,甚至在动态添加的元素上。