0

我有以下 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'));
        });
    });
});

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

令人兴奋的神秘元素!

他们来自哪里?

4

2 回答 2

3

您正在使用for...in循环数组,这是不推荐的。结果,您可能会拾取一堆您不想循环的属性,并因此得到垃圾附加。

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

于 2012-07-25T20:17:19.197 回答
1

for in ...正在创建问题,因为它也在迭代 Array 对象的属性。

将 for 循环更改为:

$.each(window.depthElems, function(i, a){
    $('body').append('<img src="' + a[0] +
                         '" style="margin-left: ' + a[1] + 
                         'px; top: ' + a[2] + 
                         'px;" data-velocity="' + a[3] +
                         '" class="depthElem" />'); 
});
于 2012-07-25T20:17:49.170 回答