我只是在学习jQuery,并试图以多种方式解决这个问题,太多无法列出,但没有成功。请帮忙!
此外,我无法弄清楚如何在此问题中添加图片,因此请选择喜欢的猫图片并修改代码以反映其名称。 (对不起)
说明:
代码:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>simple demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<!-- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<!-- DOM follows-->
<!-- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<div id="button">Add images</button></div>
<div class="image_set" id="images">
<img class="floating-box" src="test_image.jpg">
<img class="floating-box" src="test_image.jpg">
</div>
<!-- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<!-- end of DOM -->
<!-- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<script>
$(".floating-box").click(function(){
if(typeof floatingBoxMode == "undefined"){
floatingBoxMode = "full";
}
if (floatingBoxMode == "full"){
// need to set image css to fullsize
$(this).css("width", "auto");
$(this).css("height", "auto");
$(".floating-box").hide ();
$(this).show ();
floatingBoxMode = "single";
}else{
// need to set css to thumbnail
$(this).css("width", "auto");
$(this).css("height", "150px");
$(this).show ();
$(".floating-box").show ();
floatingBoxMode = "full";
};
});
$("#button").click (function () {
var s = '<img class="floating-box" src="test_image.jpg">';
$("#images").append (s);
});
</script>
<style type="text/css">
.floating-box {
float: left;
width: auto;
height: 150px;
margin: 10px;
border: 3px solid #8AC007;
max-width: 100%;
max-height: 80%;
}
.floating-box-fullsize {
float: left;
width: 100%;
height: 100%;
margin: 10px;
border: 3px solid #8AC007;
}
.image_set{
margin: 10px; /*Margins for inner DIV inside each column (to provide padding)*/
margin-top: 0;
}
</style>
</body>
</html>
答案 0 :(得分:1)
只需写下
$('.image_set').on('click','.floating-box',function(){
而不是
$(".floating-box").click(function(){
动态添加元素需要event delegation
才能使其事件被解雇
以下是 DEMO