按钮单击后无响应的元素

时间:2015-03-23 09:31:00

标签: javascript

背景

我前几天启动了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>

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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

移动

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

在构建方法中