jQuery追加删除/隐藏上一个对象

时间:2017-03-16 14:42:41

标签: javascript jquery html css

我不是百分之百确定这里发生了什么,但我想要发生的是div以50%或25%的宽度随机添加,但一个div的总长度达到75%以上或者100%使用数据属性将div的总大小加在一起。在75%时,25%的div被硬编码并且循环在total length变量设置为0之后再次开始,在100%时,total length变量设置为0并且随机性再次开始但是已经附加的div应该存在,我的问题是他们没有。

例如,如果我连续获得两个50%的div,则只有1个显示,当我console.log时,它会显示正确的数字50然后是100 ...但只有1个div显示为append。

希望我的小提琴可以解释一下情况: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>

1 个答案:

答案 0 :(得分:1)

将您的数组更改为:

var arr = ["<div class='div-50' data-width='50'></div>", "<div class='div-25' data-width='25'></div>"];