jQuery:记录Array中的元素更改并检查它的索引是如何的

时间:2014-11-30 16:55:58

标签: javascript jquery arrays

每次点击都是一步,我会在.test中添加子div,我会将所有元素更改保存在step数组

我希望它看起来像这样:

Array step [0]        = before click, 
Array step [0,01]     = after one click, 
Array step [0,01,012] = aftert two click

但它的工作原理如下:

Array step [0]        = before click, 
Array step [0,11]     = after one click, 
Array step [0,11,222] = aftert two click

fiddle example

HTML:

<div class="test"></div>
<button type="button" onclick="change()">Count Child Element</button>
<div id="result"></div>

的javascript:

var step =[];               // step is a record of changes in #test.
step.push($('.test'))        //step[0] is status of .test at very beginning.
$('#result').append(step[0][0].childElementCount+"<br>") // #result showing how many child element in #test
        var change = function (){          
        $('.test').append('<div>t</div>')       //every click will a append <div> in #test
        step.push($('.test'))                    // record this move in step[] 
        console.log('step length',step.length)   // total moves
        for ( var i = 0; i < step.length; i++ ) {
        $('#result').append(step[i][0].childElementCount)
        }
        $('#result').append("<br>")}

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您的循环迭代(i)应基于childElementCount而不是step数组长度。

我更改了代码以使用step[step.length-1]获取数组中的最后一个元素,并将for循环更改为最后一次childElementCount时停止。我还明确地调用change()让它为你创建和渲染第一个元素,以避免重复代码。

固定小提琴:http://fiddle.jshell.net/8sbq0y0k/

固定代码:

var step = []; // step is a record of changes in #test.
function change() {
    $('#test').append('<div>t</div>') //every click will a append <div> in #test
    step.push($('#test')) // record this move in step[] 
    console.log('step length', step.length) // total moves
    for (var i = 0; i < step[step.length-1][0].childElementCount; i++) {
        $('#result').append(i.toString())
    }
    $('#result').append("<br/>")
}
change(); // let change do the work for you
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test"></div>
<button type="button" class="btn btn-warning pull-right" onclick="change()">Count Child Element</button>
<div id="result"></div>