替换eval以获取表单javascript中的值

时间:2014-11-29 04:51:49

标签: javascript html

HTML脚本

<form method="POST" name="test">
<input type="hidden" name="test2" value="test3">
<input type="submit" name="submit" value="submit" onClick="send()">
</form>

的javascript

function send(){
   var form = document.test,
   a = eval("form.test2");
   alert(a.value); //test3
}

如上所示,我使用eval来获取test2值。但在某些JS检查器中,不允许使用eval ..那么如何在没有eval函数的情况下获得test2值呢?

2 个答案:

答案 0 :(得分:0)

试试这个静态示例,修改代码

&#13;
&#13;
var send = function() {
  var test2 = document.test.test2.value; //static access without eval
  alert(test2);
  return false;
}
&#13;
<form method="post" name="test">
  <input type="text" name="test2" value="test3">
  <input type="submit" name="submit" value="submit" onclick="return send()">
  <form>
&#13;
&#13;
&#13;

试试这个动态示例,修改代码

&#13;
&#13;
var find = function(str) {
  var arr = str.split('.');
  var l = arr.length,
    i = 0;
  var el = window[arr[i++]]; //<-- we refer to js and html element right from here
  while (--l)
    el = el[arr[i++]];
  return el;
};

var send = function() {
  var prop = 'document.test.test2.value'; //<-- string name of the property to access
  var el = find(prop);
  alert(el);
  return false;
}

console.log(find('document')); //sample
console.log(find('alert')); //sample
&#13;
<form method="post" name="test">
  <input type="text" name="test2" value="test3">
  <input type="submit" name="submit" value="submit" onclick="return send()">
  <form>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

试试这个:document.test.test2会为您提供带有name=test2的表单元素,然后您就可以使用它了。

<script>

function send(){

       var form = document.test;
       alert(document.test.test2.value);or form.test2.value which same as document.test.test2.value
      // alert(test2.value); //test3 
    }
</script>

<form method="POST" name="test">
<input type="hidden" name="test2" value="test3">
<input type="submit" name="submit" value="submit" onclick="send()">
</form>

**NOTE:** you should close your form tag first.