日期:2014-05-16  浏览次数:20349 次

如何将字符串转成对象?
<form   name= "form1 ">
<input   type= "text "   name= "str1 "   value= "str1 ">
<input   type= "text "   name= "str2 "   value= "str2 ">
</form>
<input   type= "button "   onclick= "test( 'form1.str1,form1.str2 ') "   value= "批量提示 ">

<script   language= "javascript ">
function   test(thisobj)
{
var   thisobjarr=   thisobj.split( ', ');
for(var   i=0;i <thisobjarr.length;i++)
alert(thisobjarr[i].value);
}
</script>

请问如何能够将str1,str2的值弹出,要求要使用数组来实现通用的批量弹出提示。

------解决方案--------------------
<form name= "form1 ">
<input type= "text " name= "str1 " value= "str1 ">
<input type= "text " name= "str2 " value= "str2 ">
</form>
<input type= "button " onclick= "test( 'str1,str2 ') " value= "批量提示 ">

<script language= "javascript ">
function test(thisobj)
{
var thisobjarr= thisobj.split( ', ');
for(var i=0;i <thisobjarr.length;i++)
alert(document.getElementsByName(thisobjarr[i])[0].value);
}
</script>
------解决方案--------------------
<form name= "form1 ">
<input type= "text " name= "str1 " value= "str1 ">
<input type= "text " name= "str2 " value= "str2 ">
</form>
<input type= "button " onclick= "test( 'form1.str1,form1.str2 ') " value= "&Aring;ú&Aacute;&iquest;&Igrave;á&Ecirc;&frac34; ">

<script language= "javascript ">
function test(thisobj)
{
var thisobjarr= thisobj.split( ', ');
for(i=0;i <thisobjarr.length;i++)

alert(eval(thisobjarr[i]).value);
}
</script>


------解决方案--------------------
function test(thisobj)
{
var thisobjarr= thisobj.split( ', ');
for(var i=0;i <thisobjarr.length;i++)
alert(eval(thisobjarr[i]+ '.value '));
}
</script>
------解决方案--------------------
eval()
------解决方案--------------------
能不用eval就尽量不用eval,因为eval的效率比较低,当然如果不在循环中使用,这个差别是比较小的。楼主的可以利用关联数组的方式解决:

<form name= "form1 ">
<input type= "text " name= "str1 " value= "str1 ">
<input type= "text " name= "str2 " value= "str2 ">
</form>
<input type= "button " onclick= "test( 'str1,str2 ') " value= "批量提示 "> //直接是name

<script language= "javascript ">
function test(thisobj)
{
var thisobjarr= thisobj.split( ', ');
for(var i=0;i <thisobjarr.length;i++)
alert(form1[thisobjarr[i]].value);
}
</script>

以上方法的弊端是form的name必须在函数中写死,但是根据这个思路,你完全也可以解决这个问题的。主要记住这点:
var myobj=new Object(); //form等等element都是Object
myobj.p==myobj[ "p "]; //这两种对myobj的子属性(可以是各种类型,包括object)的引用是等价的。不同的在后面,p是一个真正的字符串,而前面是一个引用。