您的位置:首页 > 编程语言 > Java开发

java script 陷阱

2013-12-15 00:10 134 查看
以下是JavaScript容易犯错的几个"陷阱".但注意一下,会使您的编程轻松些.

1. 最后一个逗号

如这段代码,注意最后一个逗号,按语言学角度来说应该是不错的(python的类似数据类型辞典dictionary就允许如此)。IE会报语法错误,但语义不详,你只能用人眼从几千行代码中扫描。

Js代码

Java代码







<script>

var theObj = {

city : "ShenZhen",

state : "ok",

}

</script>

[java] view
plaincopy

<span style="font-size:16px;"><script>

var theObj = {

city : "ShenZhen",

state : "ok",

}

</script> </span>

2. this的引用会改变

如这段代码:

Java代码







<input type="button" value="Gotcha!" id="MyButton" >

<script>

var MyObject = function () {

this.alertMessage = "Javascript rules";

this.ClickHandler = function() {

alert(this.alertMessage ); //行1

}

}();

document.getElementById("theText").onclick = MyObject.ClickHandler;

</script>

[java] view
plaincopy

<span style="font-size:16px;"><input type="button" value="Gotcha!" id="MyButton" >

<script>

var MyObject = function () {

this.alertMessage = "Javascript rules";

this.ClickHandler = function() {

alert(this.alertMessage ); //行1

}

}();

document.getElementById("theText").onclick = MyObject.ClickHandler;

</script> </span>

并不如你所愿,答案并不是”JavaScript rules”。在执行MyObject.ClickHandler时,在行1中,this的引用实际上指向的是document.getElementById("theText")的引用。可以这么解决:

Java代码







<input type="button" value="Gotcha!" id="theText" >

<script>

var MyObject = function () {

var self = this;

this.alertMessage = “Javascript rules”;

this.OnClick = function() {

alert(self.value);

}

}();

document.getElementById(”theText”).onclick = MyObject.OnClick

</script>

[java] view
plaincopy

<span style="font-size:16px;"><input type="button" value="Gotcha!" id="theText" >

<script>

var MyObject = function () {

var self = this;

this.alertMessage = “Javascript rules”;

this.OnClick = function() {

alert(self.value);

}

}();

document.getElementById(”theText”).onclick = MyObject.OnClick

</script></span>

实质上,这就是JavaScript作用域的问题。如果你看过,你会发现解决方案不止一种。

3. 标识盗贼

在JavaScript中不要直接使用跟HTML的id一样的变量名。如下代码:

Java代码







<input type="button" id="TheButton">

<script>

TheButton = document.getElementById("TheButton");

</script>

[java] view
plaincopy

<span style="font-size:16px;"><input type="button" id="TheButton">

<script>

TheButton = document.getElementById("TheButton");

</script></span>

IE会报对象未定义的错误。我只能说:IE 真烂.

若在TheButton之前加上var 声明,或者将TheButton改为其它名称,则不会报错.如:

Java代码







<input type="button" id="TheButton">

<script>

var TheButton = document.getElementById("TheButton");

//或

TestButton = document.getElementById("TheButton");

</script>

[java] view
plaincopy

<span style="font-size:16px;"><input type="button" id="TheButton">

<script>

var TheButton = document.getElementById("TheButton");

//或

TestButton = document.getElementById("TheButton");

</script></span>

4. 字符串只替换第一个匹配

如下代码:

Java代码







<script>

var fileName = "This is a title";

fileName=fileName.replace(" ","_");

</script>

[java] view
plaincopy

<span style="font-size:16px;"><script>

var fileName = "This is a title";

fileName=fileName.replace(" ","_");

</script> </span>

而实际上,fileName结果是"This_is a title". 在JavaScript中,String.replace的第一个参数应该是正则表达式。所以,正确的做法是这样:

Js代码

Java代码







var fileName = "This is a title".replace(/ /g,"_");

[java] view
plaincopy

<span style="font-size:16px;">var fileName = "This is a title".replace(/ /g,"_"); </span>

5. mouseout意味着mousein

事实上,这是由于事件冒泡导致的。IE中有mouseenter和mouseleave,但不是标准的。作者在此建议大家使用js库来解决问题。

6. parseInt是基于进制体系的

这个是常识,可是很多人给忽略了parseInt还有第二个参数,用以指明进制。比如,parseInt("09"),如果你认为答案是9,那就错了。因为,在此,字符串以0开头,parseInt以八进制来处理它,在八进制中,09是非法,返回false,布尔值false转化成数值就是0. 因此,正确的做法是

Java代码







parseInt("09", 10).

[java] view
plaincopy

<span style="font-size:16px;">parseInt("09", 10). </span>

7. for...in...会遍历所有的东西

有一段这样的代码:

Java代码







var arr = [5,10,15]

var total = 1;

for ( var x in arr) {

total = total * arr[x];

}

[java] view
plaincopy

<span style="font-size:16px;">var arr = [5,10,15]

var total = 1;

for ( var x in arr) {

total = total * arr[x];

} </span>

运行得好好的,不是吗?但是有一天它不干了,给我返回的值变成了NaN, 晕。我只不过引入了一个库而已啊。原来是这个库改写了Array的prototype,这样,我们的arr平白无过多出了一个属性(方法),而for...in...会把它给遍历出来。

其实,就算没有引进库.它的结果也并不是数组所有元素的乘积,因为for...in...会遍历到数组的length属性.

所以这样做才是比较安全的:

Java代码







for ( var x = 0; x < arr.length; x++) {

total = total * arr[x];

}

[java] view
plaincopy

<span style="font-size:16px;">for ( var x = 0; x < arr.length; x++) {

total = total * arr[x];

}</span>

其实,这也是污染基本类的prototype会带来危害的一个例证。

8. 事件处理器的陷阱

这其实只会存在使用作为对象属性的事件处理器才会存在的问题。比如window.onclick = MyOnClickMethod这样的代码,这会复写掉之前的window.onclick事件,还可能导致IE的内容泄露(sucks again)。在IE还没有支持DOM 2的事件注册之前,作者建议使用库来解决问题,比如使用YUI:

Java代码







YAHOO.util.Event.addListener(window, "click", MyOnClickMethod);

[java] view
plaincopy

<span style="font-size:16px;">YAHOO.util.Event.addListener(window, "click", MyOnClickMethod); </span>

这应该也属于常识问题,但新手可能容易犯错。

9. focus() 出错

新建一个input文本元素,然后把焦点挪到它上面,按理说,这样的代码应该很自然:

Java代码







var newInput = document.createElement("input");

document.body.appendChild(newInput);

newInput.focus();

newInput.select();

[java] view
plaincopy

<span style="font-size:16px;">var newInput = document.createElement("input");

document.body.appendChild(newInput);

newInput.focus();

newInput.select();</span>

但是IE会报错。这是因为当你执行fouce()的时候,元素尚未可用。因此,我们可以延迟执行:

Java代码







var newInput = document.createElement("input");

newInput.id = "TheNewInput";

document.body.appendChild(newInput);

//在0.01秒之后调用匿名函数获取焦点

setTimeout(function(){

document.getElementById('TheNewInput').focus();

document.getElementById('TheNewInput').select();}, 10);

更详细的资料参见:http://realazy.org/blog/category/javascript-dom/

[java] view
plaincopy

<span style="font-size:16px;">var newInput = document.createElement("input");

newInput.id = "TheNewInput";

document.body.appendChild(newInput);

//在0.01秒之后调用匿名函数获取焦点

setTimeout(function(){

document.getElementById('TheNewInput').focus();

document.getElementById('TheNewInput').select();}, 10);

更详细的资料参见:http://realazy.org/blog/category/javascript-dom/ </span>

10.document.write()完全替换之前页面内容

有这样一段代码:

Java代码







<h3>开始</h3>

<script type="text/jscript">

function init() {

document.write("现在时间是:" + Date() );

}

window.onload = init;

</script>

<h3>结束</h3>

[java] view
plaincopy

<span style="font-size:16px;"><h3>开始</h3>

<script type="text/jscript">

function init() {

document.write("现在时间是:" + Date() );

}

window.onload = init;

</script>

<h3>结束</h3></span>

上面代码块中的"开始"和"结束"两块不会输出.

当onload事件结束之后,如果再一次调用document.write()方法写进一段HTML,这段HTML会完全替换掉之前页面的内容.整个页面的源代码就变为了document.write()所写的内容.把上面的改为:

Java代码







<h3>开始</h3>

<script type="text/jscript">

function init() {

document.write("现在时间是:" + new Date() );

}

init()

</script>

<h3>结束</h3>

[java] view
plaincopy

<span style="font-size:16px;"><h3>开始</h3>

<script type="text/jscript">

function init() {

document.write("现在时间是:" + new Date() );

}

init()

</script>

<h3>结束</h3></span>

"开始"和"结束"就会正常输出.

11.注意你name的值.

有这样一段代码:

Java代码







<form name="myForm" action="aa.htm">

<input type="text" name="action" />

</form>

<script>

//获取form的id

alert(document.forms[0].action);

</script>

[java] view
plaincopy

<span style="font-size:16px;"><form name="myForm" action="aa.htm">

<input type="text" name="action" />

</form>

<script>

//获取form的id

alert(document.forms[0].action);

</script></span>

可输出结果不是我们想要的"aa.htm",而是一个"[object]"字符串.因为它得到的是myForm中的name为"action"的input标签的值.更详细的内容请参考

Java代码







https://bugzilla.mozilla.org/show_bug.cgi?id=322488



[java] view
plaincopy

<span style="font-size:16px;">https://bugzilla.mozilla.org/show_bug.cgi?id=322488

</span>

12.后台数据传输不会影响到前台

也许你会说这是一非常低级的错误.但我还是想说下:

页面login.htm代码

Java代码







...

xmlHttp.open("GET","check.htm",false);

xmlHttp.send();

alert(xmlHttp.responseText);

...

[java] view
plaincopy

<span style="font-size:16px;">...

xmlHttp.open("GET","check.htm",false);

xmlHttp.send();

alert(xmlHttp.responseText);

...</span>

页面check.htm代码

Java代码







window.onload=checkLogin;

function checkLogin(){

...

//如果验证失败,弹出错误

alert("登录失败");

...

}

[java] view
plaincopy

<span style="font-size:16px;">window.onload=checkLogin;

function checkLogin(){

...

//如果验证失败,弹出错误

alert("登录失败");

...

}</span>

很多人习惯用这种方法来进行登录失败的提示.但是要注意:xmlHttp发送数据的时候是进行的后台发送,它所关心的,仅仅是send之后,得到所请求URL的响应.而check.htm页面所执行的一切,都是只在后台完成.不管它怎么跳转,或者alert(),或者close().都不会在界面中有任何显示.

-----------------------------------------------------------------------------------------

在实践中,JavaScript的陷阱还有很多很多,大多是由于解析器的实现不到位而引起。这些东西一般都不会在教科书中出现,只能靠开发者之间的经验分享。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: