IT职业工程师's Archiver

那夜难忘 发表于 2007-8-10 09:18

JS中的eval和document.getElementById




eval和document.getElementById都能把字符串转化为对应的对象或是数值,但两者之间还是有区别的,请看以下几个例子:
假如页面上存在ID为aaa的标记,以下a和b得到的是一样的结果
var a=eval('aaa');
var b=document.getElementById('aaa');
var a=eval('aaa');
var b=document.getElementById('aaa');
如果页面上不存在aaa标记,则eval将发生错误,document.getElementById返回null值

另一种情况就是字符串为表达式时
alert(eval('1+1')); //返回2
alert(document.getElementById('1+1')); //返回null因为getElementById会把'1+1'看作
//标记ID进行查找
alert(eval('aaa.href')); //将返回aaa的href属性

alert(document.getElementById('aaa.href')); //和上面一样会返回null




页: [1]

Powered by Discuz! Archiver 7.0.0  © 2001-2009 Comsenz Inc.