现在的位置: 首页 > 综合 > 正文

eval()的用法

2019年11月17日 ⁄ 综合 ⁄ 共 2130字 ⁄ 字号 评论关闭

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"
    }
}

【上篇】
【下篇】

抱歉!评论已关闭.