eval()的用法

1

/*eval()的用法 :这个函数可以把一个字符串当作一个JavaScript表达式一样去执行它。*/

var the_unevaled_answer="2+3";
var the_evaled_answer=eval("2+3");
alert("the_unevaled_answer is:"+the_unevaled_answer+"the_evaled_answer is:"+the_evaled_answer);

警告框中的内容:the_unevaled_answer is:2+3 the_evaled_answer is 5

2

/*用eval获取难以索引的对象

函数功能,输入哪个图片名,则图片地址属性变为ant.gif

*/

//html

<img src="../ext-3.2.1/resources/images/access/button/arrow.gif" name="arrow"/>
这里要带上img的name属性
<img src="../ext-3.2.1/resources/images/access/button/btn.gif" name="btn"/>

//方法1

/*这种方法如果遇到多个图像就要写无数个if else语句*/

window.onload=function swapOne()
{
var the_image=prompt("change arrow or btn","");
var the_image_object;

if(the_image=="arrow") //如果输入的是"arrow",就把图像对象window.document.arrow赋给变量the_image_object
{
the_image_object=window.document.arrow;
}
else//否则就把图像对象window.document.btn赋给变量the_image_object
{
the_image_object=window.document.btn;
}

the_image_object.src="ant.gif";//把当前图像的src属性设为ant.gif
alert(the_image_object.src);//返回值为http://localhost:3312/extdown/book/ant.gif
}

//方法2

/*结果同上,但是程序会简单很多*/
window.onload=function simpleSwap()
{
var the_image=prompt("change arrow or btn","");
var the_image_name="window.document."+the_image;
var the_image_object=eval(the_image_name);
the_image_object.src="ant.gif";
alert(the_image_object.src);
}

/*
eval函数对作为数字表达式的一个字符串进行求值,其语法为:
eval(expr)
这里expr是一个被求值勤的字符串参数。如果该字符串是一个表达式,eval求该表达式的值:
如果该参数代表一个或多个javascript语句,那么eval执行这些语句,
eval函数可以用来把一个日期从一种格式(总是字符串)转换为数值表达式或数字。
*/

/*Eval函数
功能:先解释javascript代码,然后再执行它
用法:Eval(codeString)
codeString是包含有Javascript语句的字符串,在eval之后使用javascript引擎编译。

注释:
例子:eval(id+"_icon.src='/images/collapse_up.gif'");
id是之前设定的参数,而在引号中的字符串则是需要编译的

*/
function tophide(id)//
{
if(top.topframeset.rows=="31,*")
{
top.toframeset.rows="86,*";
eval(id+"_icon.src='/images/collapse_up.gif'");
eval(id+"icon.alt='Collapse The Head'");
head.style.display="block"
}
else
{
top.topframeset.row="31,*";
eval(id+"_icon.src='/images/collapse_down.gif'");
eval(id+"icon.alt='Expand The Head'");
head.style.display="none"
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值