我不是100%确定这里发生了什么,但我想要发生的是一个div随机添加在50%或25%的宽度,但一个组合的长度divs达到75%或100%以上,同时使用数据属性将div的总大小加在一起。在75%的情况下,25%的div被硬编码,并且在总长度变量被设置为0之后,循环再次开始,在100%总长度变量被设置为0并且随机性再次开始,但是已经被附加的div应该存在,我的问题是他们没有。jQuery Append删除/隐藏以前的对象
例如,如果我得到两个50%的div连续只有1个显示,当我console.log
事件它显示正确的数字50然后100 ...但只有1 div通过追加显示。
希望我的小提琴能在情况提供一些线索:https://jsfiddle.net/g8urnar3/2/
(点击按钮命名锚标记复制错误)
我的问题是,什么导致这种情况发生,为什么?
按照要求的代码...
<html>
<style>
* {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
html, body{
padding: 0;
border: none;
margin: 0;
}
a {
padding: 15px;
background: lightgrey;
text-decoration: none;
color: white;
border-radius: 4px;
}
.list {
width: 100%;
padding: 0;
margin: 0;
border: none;
}
a:hover{
cursor: pointer;
}
div {
height: 100px;
border: 2px solid black;
display: inline;
float: left;
}
.div-50{
width: 50%;
background-color: red;
}
.div-25{
width: 25%;
background-color: green;
}
</style>
<center>
<a href="#">Button</a>
</center>
<br><br>
<hr>
<div class="list">
</div>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
(function(){
var currentLength = 0;
var arr = [$("<div class='div-50' data-width='50'></div>"), $("<div class='div-25' data-width='25'></div>")];
$('a').click(function(){
console.log(currentLength);
if(currentLength < 75)
{
var random = arr[Math.floor(Math.random() * arr.length)];
currentLength = currentLength + Number($(random).attr("data-width"));
$('.list').append(random);
console.log(random);
console.log($("<div class='div-25' data-width='25'></div>"));
}
else if(currentLength == 100) {
currentLength = 0;
var random = arr[Math.floor(Math.random() * arr.length)];
currentLength = currentLength + Number($(random).attr("data-width"));
$('.list').append(random);
}
else {
currentLength = 0;
$('.list').append($("<div class='div-25'></div>"));
currentLength = currentLength + 25;
}
})
})();
</script>
请在线发布代码为文本。 jsfiddle是一个优点。 –
@LelioFaieta按要求添加 –