在JavaScript中抢占asp.net控件 [英] Grabbing asp.net controls in javascript
问题描述
我有一个页面,页面被这样的代码淹没:
I have a page where it is getting overwhelmed with code like:
var textBox = $get("<%=textState.ClientID%>");
这要求我将JavaScript放在页面内,而不是将其很好地塞在js文件中.有更好的方法吗?
This requires me to have my JavaScript inside the page instead of nicely tucked in a js file. Is there a better approach to this?
document.getElementById不起作用,因为然后我得到了如下代码:
document.getElementById doesn't work because then I end up with code like this:
var textBox = document.getElementById("originDestinationControl_textState");
或
var textBox = document.getElementById("ctl00_ContentPlaceHolder_originDestinationControl_textState");
取决于我在哪里引用这些控件(在母版页和/或用户控件内部)
depending on where I am referencing these controls (inside master pages and/or usercontrols)
推荐答案
我通常将类似的内容粘贴到要使用单独的js文件的页面中.
I normally stick something like this into pages where I want to use a separate js file.
<script type="text/javascript">
var pageNameElements = {
textbox : '<%= textbox.ClientId %>',
button : '<%= button.ClientId %>'
};
</script>
这样,您将获得一个漂亮的javascript对象,其中包含可以在js文件中使用的所有控件ID,如下所示.
This way you get a nice javascript object with all the control ids that you can use in your js file like this.
$('#' + pageNameElements.textbox)
或
document.getElementById(pageNameElements.textbox)
如果您不使用jquery.
if you're not using jquery.
这篇关于在JavaScript中抢占asp.net控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!