在“运行时”设置 html 元素值
在我的 html5 Web 应用程序中,我在加载 DOM 时设置一些 html 元素的值。使用的值取自一些 Javascript 全局变量,这些变量是在 DOM 加载开始之后、添加相应的 html DOM 元素之前确定的。现在我的代码看起来像这样:
myBtnText="some value";
//....
<input type="button" id="myBtn" onclick="DoSomeAction();" />
<script type="text/javascript">
document.getElementById("myBtn").value = myBtnText;
</script>
代码正在工作,但我想改进它,以避免 document.getElementById("myBtn") 进行的调用,并让代码更小。我正在考虑简化它,执行以下操作:
<input type="button" id="myBtn" value=/*<myBtnText>*/ onclick="DoSomeAction();" />
其中 // 是一个表达式,可以帮助获取 myBtnText 全局变量的值。
如果这可能的话,有什么想法吗?如何实现?
In my html5 web application I am setting the value of some of the html elements when the DOM is loading. The values used are taken from some Javascript global variables, which are determined after the DOM loading is started but before the corresponding html DOM element is added. For now my code looks something like:
myBtnText="some value";
//....
<input type="button" id="myBtn" onclick="DoSomeAction();" />
<script type="text/javascript">
document.getElementById("myBtn").value = myBtnText;
</script>
The code is working, but I would like to improve it, in order to avoid the call made by document.getElementById("myBtn"), and also to make the code smaller. I'm thinking to simplify it do something like:
<input type="button" id="myBtn" value=/*<myBtnText>*/ onclick="DoSomeAction();" />
where // would be an expression which can help to obtain the value of the myBtnText global variable.
Any thoughts if this would be possible, and how can this be made?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您使用 JQuery,您可以通过执行以下操作来避免调用 document.getElementById:
获取字段的值以及:
设置字段的值。您可以在这里了解更多信息:
http://api.jquery.com/val/
If you used JQuery you could do avoid the call to document.getElementById by doing something along the lines of:
to get the value of the field and:
To set the value of it. You can learn more here:
http://api.jquery.com/val/
为什么要在 DOM 准备好之前设置按钮值?这是在解析页面期间执行此操作的一种方法。
Why set the button value before DOM is ready? This is one way to do it during parsing the page.
哇,什么?这看起来是一个糟糕的语法。您是否想在 HTML 中重新发明 perl?你会用这种东西彻底破坏任何解析器!
既然您试图解决的问题似乎是代码量,为什么您不只专注于将代码减少为适当的函数,例如:
Wow, what? That looks like an awful syntax. Are you trying to reinvent perl inside HTML? You'll completely break any parser with that sort of thing!
Since the problem you are trying to solve appears to be the amount of code why don't you just focus on reducing the code to appropriate functions, like: