您的位置:首页 > Web前端 > JavaScript

Master Pages and JavaScript document.getElementById

2010-09-20 10:55 447 查看
Whenever a control is inside a Master Page, the client ID of the
control would get appended with its content placeholder ID. So, for an
element with an ID “
txtTest

”, the new client ID would look something like “
ctl00_ContentPlaceHolder1_ txtTest

”.

So, when you try to use
document.getElementById(‘txtTest’)

, you will not get access to the
txtTest

textbox in JavaScript. You need to access it by calling
document.getElementById(‘ctl00_ContentPlaceHolder1_ txtTest’)

.

To avoid hard coding of very long client IDs, we can access the control by using
document.getElementById('
<%=txtTest.ClientID%>'
)

. This will give us access to
txtTest

.
Now, this will work fine until and unless the script is inline with the
ASPX page, i.e., if the script is included as part of the ASPX page.
But, the same won’t work if you have the script in a separate .js
file and add it to the ASPX page by specifying its location.

So, in this scenario, to get access to the control, we have to hard
code the control’s ID. But hard coding is not the ideal way of coding.
To avoid this situation, what we can do is maintain a mapping between
the client ID and the server ID. In the JavaScript code, we can get the
client ID of the control by giving its server ID. This can be achieved
as shown below.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息