我想通过数组步骤[步骤顺序] [每个目标子长度] 记录元素#inner
的移动,
将#inner
从顶部.target
移动到中间.target
,应该创建一个像这样的数组:
(t1= target 1,1 = #inner length)
doc ready: [step[0][t1=1,t2=0,t3=0]]
after move: [step[0][t1=1,t2=0,t3=0],
step[1][t1=0,t2=1,t3=0]]
但在我的fiddle example中,它是这样的:
doc ready: [step[0][t1=1,t2=0,t3=0]]
after move: [step[0][t1=0,t2=1,t3=0],
step[1][t1=0,t2=1,t3=0]]
谢谢你提前帮助我。
的javascript:
var step =[]; //step is a record of changes in #test.
step.push($('.target')) //step[0] is status of .target at very beginning.
$('.target').on('click',function(){
$('#inner').appendTo(this) //move #inner
step.push($('.target')) //record this move.
for ( var i = 0; i < step.length; i++ ){ // step[] loop
$('#result').append('step ',i,': ')
// .target loop
$('.target').each(function(){$('#result').append($(this).attr('id')+"="+$(this).children('#inner').length+",")})
$('#result').append('<br/>')
}
$('#result').append('...................................<br/>')
})
HTML:
<body>
<div class="target" id="t1"><div id="inner"></div></div>
<div class="target" id="t2"></div>
<div class="target" id="t3"></div>
<div id="result"></div>
</body>
CSS:
.target {
height: 50px;
width: 50px;
border: 2px solid #666;
}
#inner {
background-color: #33F;
height: 20px;
width: 20px;
}
答案 0 :(得分:2)
这一行:
step.push($('.target')) //record this move.
你正在推动对这些元素的jQuery集合的引用,而不是我认为你想要的状态的副本。因为您正在将引用推送到这些元素,所以在step
中打印出移动列表只会反复打印每个.target
元素的当前状态。 / p>
要通过每次移动获取每个目标状态的副本,您可以将此数据存储在这样的对象数组中:(小提琴:http://fiddle.jshell.net/nbg2xaoh/)
var step = []; //step is a record of changes in #test.
$('.target').on('click', function() {
$('#inner').appendTo(this) //move #inner
saveStep(); // record this step
renderSteps(); // show steps history
})
function saveStep() {
var newStep = {};
$(".target").each(function() {
newStep[this.id] = $(this).children().length;
});
step.push(newStep);
}
function renderSteps() {
$.each(step, function(idx, item) {
var output = [];
for (var prop in item) {
output[output.length] = prop + "=" + item[prop];
}
$("#result").append("step " + idx.toString() + ": " + output.join(',') + "<br/>");
});
$("#result").append("..................................<br/>");
}
saveStep(); // save intial state; step[0] is status of .target at very beginning.
renderSteps(); // display beginning state
.target {
height: 50px;
width: 50px;
border: 2px solid #666;
}
#inner {
background-color: #33F;
height: 20px;
width: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="target" id="t1">
<div id="inner"></div>
</div>
<div class="target" id="t2"></div>
<div class="target" id="t3"></div>
<div id="result"></div>