<分区>
标签 javascript jquery html css
<分区>
我是编程新手,现在正在学习 jquery。 我必须制作简单的 Etch-A-Sketch 应用程序。我正在尝试在 jsfiddle.net 中制作它 一切安好?但是当我输入网格的宽度和高度时,它做错了。 示例:我输入 10(在宽度提示中)和 10(在高度提示中),但结果高度为 20,宽度为 15。 这是我的 jquery 代码:
$(document).ready(function(){
$('button').click(function(){
var height = prompt("Enter your height (less than 64)");
var width = prompt("Enter your width (less than 64)");
if (height > 64){
alert("You can't make height more than 64!");
}
if (width > 64){
alert("You can't make width more than 64!");
}
for (i=0; i<height; i++){
$('#container').append('<ul></ul>');
}
for (i=0; i<width; i++){
$('ul').append('<li><li>');
}
$('li').hover(function(){
$(this).css('background-color', 'red');
});
});
});
这是 html:
<body>
<quotes>Press the button to create your own Grid</quotes><br/>
<button>New Grid</button>
<div id = "container"></div>
</body>
这是 CSS:
quotes{
margin-left: 25px;
margin-top: 10px;
}
button{
margin-left: 130px;
margin-top: 4px;
}
ul{
margin: auto;
padding: auto;
}
ul li{
list-style: none;
display: inline-block;
height: 20px;
width:30px;
border: 1px solid black;
}
它可以工作,但方式不对。我的错误在哪里?请帮助我理解它。 感谢关注
最佳答案
您的代码没有按预期工作,因为您没有关闭 <li>
在 HTMLString 中:
$('ul').append('<li><li>');
所以 jQuery 会创建两个 <li>
并将其附加到所有现有的 <ul>
在每次迭代中
应该是$('ul').append('<li></li>');
或者只是 $('ul').append('<li>');
或 $('ul').append($('<li/>'));
您可以创建如下所示的网格:
$(document).ready(function () {
$('button').click(function () {
var height = prompt("Enter your height (less than 64)");
var width = prompt("Enter your width (less than 64)");
if (height > 64) {
alert("You can't make height more than 64!");
return;
}
if (width > 64) {
alert("You can't make width more than 64!");
return;
}
for (i = 0; i < height; i++) { // iterate n number of times according to height
// upon each iteration create one ul
$("<ul/>").appendTo('#container')
// create n number of li according to width and append them to the ul
.append(new Array(parseInt(width)+1).join("<li></li>"));
}
$('li').hover(function () {
$(this).css('background-color', 'red');
});
});
});
quotes {
margin-left: 25px;
margin-top: 10px;
}
button {
margin-left: 130px;
margin-top: 4px;
}
ul {
margin: auto;
padding: auto;
}
ul li {
list-style: none;
display: inline-block;
height: 20px;
width:30px;
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<quotes>Press the button to create your own Grid</quotes>
<br/>
<button>New Grid</button>
<div id="container"></div>
关于javascript - jquery 不能正常工作或者我是个笨蛋,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27205048/