简体   繁体   English

使用JavaScript在usercontrol中选择元素

[英]Selecting elements in a usercontrol using JavaScript

I have a web form that contains a usercontrol and I would like to be able to access the html elements within the usercontrol from the form page using javascript. 我有一个包含usercontrol的Web表单,我希望能够使用javascript从表单页面访问usercontrol中的html元素。

I tried the following: 我尝试了以下方法:

document.getElementById('<%= usercontrol.clientid %>')

but this returned null . 但是这返回了null

I had a look around with firebug and found that the tags in the usercontrol render with clientids like usercontrolid_myelement. 我用firebug环顾四周,发现usercontrol中的标签使用像usercontrolid_myelement这样的clientid进行渲染。 I'm guessing that something like this might work: 我猜这样的事可能有用:

document.getElementById('<%= usercontrol.clientid %>'+'_myelement')

Is there a better/nicer way of doing this? 这样做有更好/更好的方法吗?

Your problem is likely due to the javascript running before the html is fully loaded. 您的问题可能是由于在html完全加载之前运行了javascript。

following results in null 以下结果为null

<head>
  <script type="text/javascript">
    alert(document.getElementById('main'));
  </script>
</head>
<body>
  <div id="main">

  </div>
</body>

this is better and returns the object 这样更好并返回对象

<head>
  function foo(){alert(document.getElementById('main'));}
</head>
<body onload="foo();">
  <div id="main">

  </div>
</body>

If your using .net 4 then you can stop the generated ids from being in that weird format. 如果您使用.net 4,那么您可以阻止生成的ID处于那种奇怪的格式。 Just add this property the asp.net ClientIDMode="Static" eg 只需添加此属性asp.net ClientIDMode =“静态”例如

That should make it easier to access in the dom from javascript. 这应该可以让你更容易从davascript访问dom。

I have seen through your question with my psychic powers! 我已经通过你的心灵力量看到了你的问题!

Your problem is that your serverscript in your main page can't access the ASP.net elements of your usercontrol. 您的问题是您的主页中的serverscript无法访问您的usercontrol的ASP.net元素。

The solution is to expose the elements, or just the ClientIDs of the elements you need, through properties in the usercontrol. 解决方案是通过usercontrol中的属性公开元素,或者只显示所需元素的ClientID。 Then you can use the ClientIDs in Javascript like you want to. 然后,您可以像Javascript一样使用JID中的ClientID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM