javascript构造函数中的getElementById
getElementById in javascript constructor
我有一个关于所附代码片段的问题。你觉得元素的选择怎么样。我按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都已加载到内存中。
希望能有所帮助。
相关文章:
- reactjs this.refs vs document.getElementById
- 如何通过adf中的document.getElementById获取inputText字段值
- 无法获取文档.GetElementById工作正常
- document.getElementById(“st”).click();不起作用
- Javascript:Can't使用getElementById获取元素
- 如何使用“;getElementById”;在一个循环中
- Javascript GetElementByID has no value
- document.getElementById并使用id名称
- document.getElementById在js中不起作用
- document.getElementById.style.backgroundImage not working
- 如何从document.getElementById()中获取UniqueID
- 从输入框、Javascript、getElementById获取值
- 什么'这个javascript代码getElementById有问题
- DOMDocument getelementbyid conflict?
- 如何从getelementbyid用javascript编写变量
- inline svg--getElementById在Opera中不起作用
- 在init function()中调用getElementById(“..”),而不是想用它做点什么的函数
- 将global.getelementbyid连接到单个变量中
- 未捕获的类型错误:未定义不是上的函数.GetElementByID
- document.getElementById(..) is null