gpt4 book ai didi

javascript - 附加时出现神秘元素

转载 作者:行者123 更新时间:2023-11-28 16:15:20 24 4
gpt4 key购买 nike

我有以下 PHP 和 JS:

<?php
// Here's where the array of objects is built
$depthElements = array(
array('http://placehold.it/300x300',-150,100,0.8),
array('http://placehold.it/200x300',-270,458,0.7)
);
?>
<script>
var depthElems = <?php echo(json_encode($depthElements)); ?>;
</script>

它构建了一个多维PHP数组,然后将它们打包给JS:

jQuery(document).ready(function($) { 

// Create and position the elements on the page
for (element in window.depthElems) {
var a = window.depthElems[element];
$('body').append('<img src="' + a[0] +
'" style="margin-left: ' + a[1] +
'px; top: ' + a[2] +
'px;" data-velocity="' + a[3] +
'" class="depthElem" />');
}

$(document).scroll(function () {
var topDist = $(document).scrollTop();
$('.depthElem').each(function () {
$(this).css('margin-top', -topDist*($(this).attr('data-velocity')+'px'));
});
});
});

这对我来说似乎很有意义,但由于某种原因,页面上有一堆我没有要求的额外元素:

Exciting mystery elements!

他们从哪里来?

最佳答案

您正在使用for...in循环数组, which is not recommended 。因此,您可能会获取一堆您不想循环的属性,并因此获得垃圾附加。

改用常规 for 循环 ( for (var i = 0; i < array.length; i++) ),它应该按预期工作。

关于javascript - 附加时出现神秘元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11657897/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com