Heim >Web-Frontend >js-Tutorial >客户端脚本中常常出现的一些问题和调试技巧_基础知识

客户端脚本中常常出现的一些问题和调试技巧_基础知识

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-05-16 19:21:341332Durchsuche
1.出错情况:语法错误

<script> <BR>document.write("never-online"; <BR></script>
解释:上面的示例是一个典型例子,方法名都要用()括起来()里的是参数。
也许有人不屑一顾,但在论坛中。这种错误不在少数。
Tips:这种问题解决起来比较简单,一般都可以解决。

2.出错情况:引号用法不正确
<script> <BR>s="alert("never-online")"; <BR></script>
解释:在javascript或是vbscript的编程中,引号出错的机率是很大的,不管是有多丰富的编程经验,遇到大量的字符串拼接,或者是一不小心的敲错'("),都会出现“语法错误”或者是“缺少'”。
Tips:在进行大量的字符拼接时,需要注意引号的转义用法。如上面的就可以写成:s="alert(\"never-online\")";或者s='alert("never-online")';
相关链接:js技巧--转义符"\"的妙用 - http://blog.csdn.net/bluedestiny/archive/2006/03/15/625061.aspx

3.出错情况:未知软性错误

<script> <BR>cntMax=100; <BR>div=document.createElement("DIV"); <BR>document.body.appendChild(div); <BR>var myFun=function() { <BR>for(var i=0;i<cntMax;i++); <BR>div.innerHTML+="<b>i: " +i+ "<br/>"; <BR>div.innerHtml+="http://www.never-online.net"; <BR>} <BR>myFun(); <BR></script>

运行出来,没有提示错误,这给人一个错觉,像类似这种软性错误是比较难找的。
所以平常写程序,必须细心。
Tips:编程时应该注意自己的习惯,像在for(var i=0;i
4.出错情况:对语言的理解错误
最常见的可能算是this关键字了,这里就举一个例子来说明
this语义:指向当前对象的指针。
例子:
<script> <BR>function a() { <BR>this.m = "never-online"; <BR>this.f = function() { <BR>alert(this.m); <BR>} <BR>} <BR>var b = new a(); <BR>b.f(); <BR></script>
相信上面这个例子,很多人都理解。this指向的是a()
再看下面这个例子:
div container - onmouseover handle

<script> <BR>function a() { <BR>this.m = val = 'never-online'; <BR>var div = document.getElementById("div1"); <BR>div.onmouseover=function() { <BR>alert(this.m); <BR>} <BR>alert(this.m); <BR>} <BR>a(); <BR></script>
这一个例子,有些兄弟可能就不能理解了,仔细看看之后,也可以预测输出结果。
解释:this.m = val = 'never-online'这一句是赋值,其中的this.m中的this指向的是当前对象a();
而div.onmouseover里的this指的对象是document.getElementById("div1")这个对象,(因为div并不属于a对象)即相当于把代码写在这里:
div container - onmouseover handle

因此在div.onmouseover的function里this.m出现undefined并不奇怪。 
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn