-4

请帮助修复脚本。

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>

1,后出现问题2。表示控制台即指定属性player。但是这个属性被定义为

player = document.getElementById ('player')

任何方法都可以访问它。

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

4

1 回答 1

0

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

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

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

Once I figured out the actual problem, it was simply a case of you trying to find the element before it exists (as the first step of your KalininHuyak method/class).

I moved the selector into the append (for now). You simply need to find the player object after it has been appended.

于 2013-09-26T08:19:12.297 回答