Javascript 无法在 Html 服务器控件上工作?
我正在使用 ASP.Net 编写一个网站。
我将有很多 html 通用控件
,例如
;
等等..我有一些 onclick
javascript 函数,onmouseover
javascript 函数..
它们工作正常..
然后我需要控制它们在服务器端。
所以,我添加 runat="server"
..
之后,所有 javascript 都不再工作了..
我知道它们不再工作,因为所有事件现在都返回到服务器端。
那么,有什么办法可以让它们工作吗?
例如,
<div id="myDiv1" onclick="myfunction(para1)"><img src="..." /></div>
上面的代码正在工作..
<div id="myDiv1" runat="server" onclick="myfunction(para1)"><img src="..." /></div>
上面的代码不起作用...
我可以让它工作,可能是
<div id="externalDiv1" onclick="myfunction(para1)"><div id="myDiv1" runat="server" ><img src="..." /></div></div>
有其他方法吗?
I am writing a website with ASP.Net
.
I will have lots of html generic controls
like <div> <span>
and so on..
I have some onclick
javascript functions, onmouseover
javascript functions..
They are working fine..
Then I need to control them on the server side.
So, I add runat="server"
..
After that, all the javascripts aren't working anymore..
I understand they aren't working coz all the events are now going back to server side.
So, is there anyway to make them work??
For eg,
<div id="myDiv1" onclick="myfunction(para1)"><img src="..." /></div>
the above code is working..
<div id="myDiv1" runat="server" onclick="myfunction(para1)"><img src="..." /></div>
the above code is not working...
I can make it work, probably by
<div id="externalDiv1" onclick="myfunction(para1)"><div id="myDiv1" runat="server" ><img src="..." /></div></div>
Is there any other way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
就 JavaScript 而言,服务器端或客户端控件没有区别。所有服务器端控件最终都会呈现为普通 HTML 控件。如果您的 javascript 函数无法正常工作,可能是因为您通过错误的 id 访问它们,因为通过将它们设为服务器端控件,它们现在可以具有遵循
_
。例如,这样声明的 span 元素
可能最终会呈现为:
ASP.NET 4.0 有一个称为
CliendIDMode
的功能,可以将其设置为static
,这意味着标记上的 id 在页面呈现后将保持不变。Server-side or client-side controls makes no difference as far as javascript is concerned. ALL server-side controls end up being rendered as normal HTML controls. If your javascript functions are not working might be because you are accessing them by the wrong id since by making them server-side controls they can now have ids that follow a pattern like
<parent_id>_<control_id>
.For example, a span element declared like this:
may end up being rendered as:
ASP.NET 4.0 has a feature called
CliendIDMode
which can be set tostatic
, meaning, that your ids on the markup will stay unchanged after the page is rendered.我假设您使用 document.getElementById() 通过 id 获取元素。如果您使用母版页,服务器控件的ID在渲染到页面后会发生变化,在这种情况下,您必须使用其ClientID
例如
I assume that you used document.getElementById() to get an element by its id. If you are using master pages, the IDs of server controls will be changed after rendering to the page, in that case, you have to use its ClientID
for e.g.