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

标签 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 值?

最佳答案

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

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

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

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
<form method="post" name="test">
  <input type="text" name="test2" value="test3">
  <input type="submit" name="submit" value="submit" onclick="return send()">
  <form>

关于javascript - 替换 eval 以获取表单 javascript 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27198994/

相关文章:

html - 有没有一种方法可以在没有复杂设置的情况下将标签与 CSS 中的缺失值右对齐?

javascript - 如何在动态创建和填充后设置文本框或下拉列表框的样式?

html - 如何知道在哪里呈现更多信息

javascript - Accept Header在javascript中的应用

javascript - 云函数上传到github后隐藏了?

html - 将不同的媒体样式表与打印样式表一起使用

html - 为什么边框: 5px dashed not come out as dashed in Firefox?

javascript - 对所有国家的用户使用中文谷歌地图 API 是一个好主意吗?

javascript - MySQL UPDATE 只更新整数,不更新字符串

javascript - 完整日历 : How to support one tap and no long tap