我正在学习Head First系列中的jQuery,并在其中一个例子上工作,我需要找到最后选定的元素。jQuery - 找到最后选定的元素
下面是我从第2章中得到的结果:该页面包含四个图像,当用户点击它们时,会在每幅图像的底部显示随机折扣消息。为了让事情看起来更有意思,我将slideUp()
函数添加到我从同一本书中学习第1章的消息中。
下面是我已经走了多远:当用户点击其中一个图片时,随机折扣消息向下滑动以显示其消息。当用户单击任何其他图像时,先前的消息会滑回,并且新的随机折扣消息会在点击的图像下滑下。这是我的代码的简化版本。
$('.jumpDiv').click(function() {
$('.jumpDiv').children('.discountDiv').slideUp();
$('.jumpDiv p').remove();
var discount = Math.floor((Math.random() * 5) + 5);
var msg = '<p>Your discount is ' + discount + '%</p>';
$(this).children('.discountDiv').append(msg);
$(this).children('.discountDiv').slideDown();
});
.jumpDiv{
float:left;
}
#main{
border:1px solid;
height:500px;
width:auto;
background-color: grey;
}
#main .jumpDiv{
border-right: 1px solid;
border-bottom: 1px solid;
height:245px;
width:245px;
font-size:20px;
}
#main .jumpDiv>div{
text-align:center;
background-color:#fee;
cursor: pointer;
}
.discountDiv{
text-align: center;
display:none;
border:1px solid;
border-bottom-left-radius: 10px;
border-bottom-right-radius: 10px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<body>
<div id="main">
<div class="jumpDiv">
<div> Click Here</div>
<div class="discountDiv">
</div>
</div>
<div class="jumpDiv">
<div> Click Here</div>
<div class="discountDiv">
</div>
</div>
<div class="jumpDiv">
<div> Click Here</div>
<div class="discountDiv">
</div>
</div>
<div class="jumpDiv">
<div> Click Here</div>
<div class="discountDiv">
</div>
</div>
</div>
<script
\t \t \t src="https://code.jquery.com/jquery-3.2.1.js"
\t \t \t integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
\t \t \t crossorigin="anonymous"></script>
</body>
我需要删除的毛刺,如果用户点击同一div反复,打折消息的div应该保持原样,并且只更新随机生成的内容。如果用户再次点击了相同的div,我该如何阻止这个div滑动回来。有没有办法访问最后点击的元素,并以某种方式停止折扣消息,以便在更新消息之前进行备份。
感谢11thdimension,我一直在想同样的观点,但并没有想出如何执行这个想法...此外,你的解决方案有一个更好,更合适的版本,我原来计划...感谢束... –
不客气! – 11thdimension