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/