javascript构造函数中的getElementById

getElementById in javascript constructor

本文关键字:getElementById 构造函数 javascript      更新时间:2023-09-26

我有一个关于所附代码片段的问题。你觉得元素的选择怎么样。我按id选择了元素,但选了两次。当我能够将变量初始化为元素对象时,我正在寻找一个解决方案。

<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
function Navigation(){
    stepValue = 50;
    horizontalPosition = 0;
    verticalPosition = 0;
    this.step = function(direction){
        if(direction=="left"){
            horizontalStep(horizontalPosition-=stepValue);
        } else if(direction=="right"){
            horizontalStep(horizontalPosition+=stepValue);
        } else if(direction=="up"){
            verticalStep(verticalPosition-=stepValue);
        } else if(direction=="down"){
            verticalStep(verticalPosition+=stepValue);
        }
    }
    horizontalStep = function(value){
        document.getElementById('slider').style.left=horizontalPosition;
    }
    verticalStep = function(value){
        document.getElementById('slider').style.top=verticalPosition;
    }
}

Navigation.prototype = {
    left: function(){
        this.step("left");  
    },
    right: function(){
        this.step("right");
    },
    up: function(){
        this.step("up");
    },
    down: function(){
        this.step("down");
    }
}
var Nav = new Navigation();

</script>
</head>
<body>
<input type="button" onclick="Nav.left()" id="left"  value="Left" />
<input type="button" onclick="Nav.right()" id="right" value="Right" />
<input type="button" onclick="Nav.up()" id="up"  value="Up" />
<input type="button" onclick="Nav.down()" id="down" value="Down" />
<div id="slider" style="width: 200px; height: 200px; background: #ccc000; position: relative;">hello</div>
</body>
</html>

可以在构造函数中初始化变量,而不需要像这样的窗口加载(项变量):

   function Navigation(){
     stepValue = 50;
     horizontalPosition = 0;
     verticalPosition = 0;
     item = document.getElementById("slider");
     ....

如果不可能,我将与jquery结合。我认为这将是一个解决方案。

谢谢你的回答和意见!

胫骨

您应该这样做:

function Navigation() {
    var item = document.getElementById('slider');
    // ...
}
var Nav = null;
$(function () {
    Nav = new Navigation();
});

使得代码直到DOM准备好并且CCD_ 1元素存在才运行。只有到那时,您才能从DOM中获取它并将其保存在变量中。

您可以将<script></script>放在HTML中body标记的末尾之前,如下所示::

<html>
<head>
</head>
</body>
<!-- put all your html here before the script tag -->
<script>
    //place your script here
</script>
</body>
<html>

这将确保在脚本执行之前,所有DOM都已加载到内存中。

希望能有所帮助。