gpt4 book ai didi

jquery - 动态定位 div 的最后一个子元素(匹配游戏)

转载 作者:行者123 更新时间:2023-12-01 01:06:18 24 4
gpt4 key购买 nike

我正在制作一个匹配游戏,想法是在两侧附加 5 个图像,然后在左侧附加第 6 个图像,用户必须单击最后添加的图像,然后它将被删除,另外 6 个图像将附加到左侧(右侧 5 个),然后用户必须单击左侧 div 中的第 11 个图像,第一次单击时,所有内容都会按预期运行,但之后,当我单击最后添加的图像没有任何反应!!.

我尝试了各种访问 div 的最后一个子元素的方法,但它们都返回了相同的问题。

这是整个代码::

<!DOCTYPE html>
<html>
<head>
<title>Pick The Difference !</title>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.0/jquery-ui.min.js"></script>
</head>
<style type="text/css">
body {
display: flex;
flex-wrap: wrap;
margin:auto;
width:1000px;

background-color: blue;
}
#left {
width : 495px;
height : 600px;
background-color : yellow;
}
#mid {
width : 10px;
height : 600px;
background-color : black;
}
#right {
width : 495px;
height : 600px;
background-color : orange;
}
div {

}
img:hover{
background-color: blue;
}
img {
position: absolute;
border:10px;
border-radius: 300px;
height: 100px;
width: 100px;
}
.leftimg{
margin-left: 181px;
}
.rightimg{
margin-left: 691px;
}
</style>
<body>
<div id="left"></div>
<div id="mid"></div>
<div id="right"></div>
</body>
<script type="text/javascript">
$(document).ready(function(){
function generate(){

for (var i=0; i<5; i++) {
var randTop = Math.floor(Math.random()*500);
var randLeft = Math.floor(Math.random()*401);
$("#left").append('<img class="leftimg" src="http://bahaazidan.pe.hu/Smiley.png" style="top:' +randTop+'px;'+'left:'+randLeft+'px";'+ '/>');
$("#left").append('<img class="rightimg" src="http://bahaazidan.pe.hu/Smiley.png" style="top:' +randTop+'px;'+'left:'+randLeft+'px";'+ '/>');
}
$("#left").append('<img class="leftimg" src="http://bahaazidan.pe.hu/Smiley.png" style="top:' +Math.floor(Math.random()*500)+'px;'+'left:'+Math.floor(Math.random()*401)+'px";'+ '/>');
}
generate();
$("#left img:last-child").click(function(){
$("#left img:last-child").remove();
generate();
});

});
</script>
</html>

最佳答案

您的代码:

$("#left img:last-child").click(function() {
$("#left img:last-child").remove();
generate();
});

像这样在 $(document).ready() 上运行的 .click() 事件处理程序将专门绑定(bind)到它在运行时匹配的元素 - 但它不会动态地将 future 的元素与该选择器匹配。

在不变的父元素上使用 .on() 处理程序将解决此问题:

$("#left").on('click', 'img:last-child', function() {
$(this).remove();
generate();
});

关于jquery - 动态定位 div 的最后一个子元素(匹配游戏),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41401419/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com