Home > Web Front-end > JS Tutorial > body text

javascript中var的重要性分析_基础知识

WBOY
Release: 2016-05-16 16:14:35
Original
2027 people have browsed it

本文实例分析了javascript中var的重要性。分享给大家供大家参考。具体分析如下:

javascript 的 var 作用是声明变量。

一般情况下不写都不会出错,但有些情况如果不写,会有不同的结果。先看下面的示例:

<div id="a"></div> 
<script type="text/javascript"> 
a = 1; 
alert(a); 
</script>
Copy after login

上面这个例子在FF Chrome执行不会有问题,能输出1。但在IE运行呢? 报错:“object doesn't support this property or method”。

因为IE下可以直接通过id获取DOM元素的引用,因此 a=1 就会报错,因为此时的a是 id="a" 的DOM元素。

如果把

这句去掉,则不会有问题。为了避免这种冲突情况,建议一定要用var声明变量。

希望本文所述对大家的javascript程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!