我的播放器对象上无法使用的属性

时间:2013-09-26 07:54:07

标签: javascript jquery

请帮助修复脚本。

JS:

//--- PLUGIN kalininHuyak IMPLEMENTATION ---

function KalininHuyak(options){

    // --- properties ---
    var huyakWrap = options.huyakWrap,
        playerOffset = 10,
        player = document.getElementById('player'),
        xPosition = 200,
        yPosition = 500;

    // --- methods ----
    playerShip = {          
        createPlayer: function (){  
            var player = $('<div />',
                {
                    class: 'player',
                    id: 'player'
                }
            );  
            return player;
        },      
        appendPlayer: function ( player, xPosition, yPosition){
            player.appendTo('#huyakWrap');
            player.attr('style', 'left: ' + xPosition + 'px; top: ' + 
                yPosition + 'px'
            );
        },
        movePlayer: function (direction, offset){
            var playerPositionX = player.style.left,
                currentOffset = parseInt(playerPositionX, 10),
                preCurrentOffset = currentOffset + (offset * direction);
            if(preCurrentOffset < 0){
                preCurrentOffset = 0;
            }
            else
                if(preCurrentOffset > 920){
                     preCurrentOffset = 920;
                }
            player.style.left = preCurrentOffset  + 'px';
        }
    }

    // --- init ---
    playerShip.appendPlayer(playerShip.createPlayer(), xPosition, yPosition );

    // --- handlers ---
    function onKeypress(keyCode){
        var direction;

        if(keyCode == 49){
            direction = -1;
        }
        else
            if(keyCode == 50){
                direction = 1;
            };
        playerShip.movePlayer(direction, playerOffset);
    }

    // --- events ---
    $(window).keypress( function(e)
        {
            onKeypress(e.which);
        }
    );
};


var kalininHuyak = new KalininHuyak(
    {
        huyakWrap: document.getElementById('huyakWrap')
    }
);  

HTML:

<div id="huyakWrap" class="huyak_wrap">

</div>

12后出现问题。表示指定属性player的控制台。但是这个属性被定义为

player = document.getElementById ('player')

任何方法都可以访问它。

是一个活生生的演示http://prozaik.16mb.com/js3/huYak2/

1 个答案:

答案 0 :(得分:0)

JSFiddle:http://jsfiddle.net/fjdC9/1/

appendPlayer: function (player, xPosition, yPosition){
    player.appendTo('#huyakWrap');

    player.attr('style', 'left: ' + xPosition + 'px; top: ' + yPosition + 'px');
    $player = $('#player');
},  

一旦我弄清楚了实际的问题,这只是你试图在元素存在之前找到它的情况(作为你的KalininHuyak方法/类的第一步)。

我将选择器移动到追加(现在)。您只需要在附加后找到播放器对象