由于放置不当,JS代码无法正常工作 [英] JS code not working because of bad placement

查看:99
本文介绍了由于放置不当,JS代码无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JavaScript新手。



我知道一个全局变量应该在整个页面都可见,但这似乎并不是这样。 / p>

在HTML头部我有< script> 标签,我定义了一个全局变量,但是这个变量没有存在于HTML正文中的< script> 标签中。我检查了 alert(varname == null)



我不明白。



代码未放在一起的原因是文档要完成加载,以便脚本能够访问它正在处理的内容。有没有一个标准的方式来做到这一点?



我的代码无法在任何地方工作是荒谬的 - 不能在因为 < div> 尚未加载,因此无法在< body> 中工作,因为全局变量不可见! / p>

编辑



我使用var varname;定义全局变量没有给他们一个价值,显然这不算是他们的定义。将其更改为varvarname = [];现在它的工作原理。如果你想在完成加载时运行一个JavaScript代码,最好的做法是来创建一个在onload方法中调用的函数。

HTML代码

 < body onload =changediv('2');> 
< div id =1> 11111111111 1111111111111 111111111< / div>
< div id =2> 222222c 2222222222222 22222222< / div>
< div id =3> 23333333 3 333 3 3 3 3 3 33333 3< / div>
< div id =4> 4444 4 4 44444 4 4 4 4444< / div>
< / body>

Javascript函数

  function changediv(id){
var d = document.getElementById(id);
d.style.color =#ccc;

这里有一个关于JSBIN的例子



http://jsbin.com/ajawic/1/edit p>

通过这种方式,您可以在使用前确保对象存在。


I am new to JavaScript.

I understand that a global variable should be visible all over the page, but this doesn't seem to be the case.

In the HTML head I have <script> tags where I defined a global variable, but this variable does not exist in the <script> tags in the HTML body. I checked with alert(varname==null).

I do not understand this.

The reason the code is not placed together is for the document to finish 'loading', so that the script will be able to access the it is working on. Is there a standard way to do this?

It is ridiculous that my code cannot work in either places - can't work in the because the <div> isn't loaded yet and can't work in the <body> because the global variable isn't visible!

EDIT

I defined my global variables using "var varname;" without giving them a value, apparently that didn't count as defining them. Changed it to var "varname = [];" and now it works. Initiating to null didn't work either.

解决方案

if you want to run a javascript code on finish loading, a best practice is to make a function that is called in the onload method.

HTML Code

<body onload="changediv('2');">
    <div id="1">11111111111 1111111111111 111111111</div>
    <div id="2">222222c   2222222222222 22222222</div>
    <div id="3">23333333 3 333 3 3 3 3 3 33333 3</div>
    <div id="4">4444 4  4 44444 4 4 4 4444 </div>
</body>

Javascript function

function changediv(id){
    var d = document.getElementById(id);
        d.style.color = "#ccc";
}

here you have an example on JSBIN

http://jsbin.com/ajawic/1/edit

In this way, you ensure that the object exists before use.

这篇关于由于放置不当,JS代码无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆