如何使用变量值作为 dom 树的一部分?
我知道我可以使用 eval,但根据我所读到的内容,eval 是邪恶的!我可以使用其他替代方案吗?
var key = "foo"; //hardcoded for this example, but should actually be dynamic
console.log(document.myform.foo.value); //prints whatever value its supposed to be
document.myform[key].value = "bar"; //<-- what i want to do
console.log(document.myform.foo.value); //prints "bar"
还有jquery。 jquery 可以让这个更容易操作吗?
I understand that I can use eval, but based on what I've read, eval is evil! Are there alternatives I can use?
var key = "foo"; //hardcoded for this example, but should actually be dynamic
console.log(document.myform.foo.value); //prints whatever value its supposed to be
document.myform[key].value = "bar"; //<-- what i want to do
console.log(document.myform.foo.value); //prints "bar"
Also have jquery. Is this something jquery can make easier to manipulate?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该脚本没有任何问题。它将按您的预期工作。基本上,任何时候你在 JavaScript 中有
.
,它后面的值都可以用数组表示法来表示(这就是你所拥有的)There is nothing wrong with that script. It will work as you expect. Basically, any time you have a
.
in JavaScript, the value after it can be notated with array notation (which is what you have there)jQuery 的全部内容是访问 dom 树,如果 key 是一个 id,您可以像这样使用 jQuery:
有一整套选择器可以使使用 jQuery 轻松访问 dome (http://api.jquery.com/category/selectors/):
查看上面的选择器链接,它是 jQuery 如此出色的重要原因好的。
jQuery is all about accessing the dom tree, if key is an id you can use jQuery like so:
There are a whole host of selectors to make accessing the dome easy with jQuery (http://api.jquery.com/category/selectors/):
Check-out the selectors link above, its a big part of why jQuery is so nice.