使用复选框更改对象可见性?
如果以前有人问过这个问题,但我找不到它,我真的很抱歉。
开发 ASP.NET/C# Web 应用程序。
我正在后面的代码中创建一个标签并将其添加到页面(所有代码都在后面的代码中编码,而不是在设计页面中)
现在我有一个复选框,我想根据是否选中该复选框来更改标签的可见性(显示)或如果没有(隐藏)。
我尝试使用更新面板。但由于标签是在代码中生成的,因此每次出现部分回发时我都必须再次生成它。我不想要这样。
有没有办法用 javascript 来避免回发?其他解决方案也受到赞赏。
非常感谢您的帮助
i'm really sorry if this question have been asked before but I couldn't find it.
Working on a ASP.NET/C# web application.
i am creating a label in the code behind and adding it to the page (all coded in the code behind and not in design page)
Now I have a check-box I want to change the visibility of the label depending if the checkbox is checked (show) or if not (hide).
I tried to use an update panel. But since the label is generated in code I have to generate it again everytime there is a partial postback. and I don't want that.
Is there a way to do this with javascript to avoid post-backs? other solutions are also appreciated.
Thank you very much for any help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
将此代码放入页面Load中。
添加对 jQuery javascript 的引用并将其作为 HTML 放置在下面。
如果您需要创建动态控件,请尝试使用 AJAX (jQuery)。
Put this code in the page Load.
Add the reference to the jQuery javascript and place it as HTML below.
Try to use AJAX (jQuery) in case you need to create dynamic controls.
你走在正确的轨道上。您可以通过使用客户端脚本来执行此操作,从而避免使用 UpdatePanel 控件和 AJAX 调用的开销和复杂性。
您需要定义一个 JavaScript 函数来触发网页上复选框的 onClick 事件:
我假设您正在从代码隐藏中向页面添加 ID 为“lbl”的标签。确保将标签设为 Page 类的 Protected 成员,以便您可以使用服务器标记从 aspx 页面访问它,以便在 JavaScript 中调用 document.getElementById 时检索正确的 ID。这很重要。
因此,您的 aspx 页面上的 JavaScript 代码如下所示:
You are on the right track. You can avoid the overhead and complexity of using UpdatePanel controls and an AJAX call by using client-side script to do this instead.
You'll want to define a JavaScript function to fire for the onClick event of the checkbox on your web page:
I'll assume you're adding a label with ID "lbl" to the page from your code-behind. Make sure you make the label a Protected member of the Page class so you can access it from the aspx page using a server tag to retrieve the correct ID for when you call document.getElementById in JavaScript. This is important.
So here's what your JavaScript code on your aspx page will look like:
为什么不想在每次回发时加载标签控件?使用 ASP.NET,整个页面都会通过每次回发来加载,并且视图状态会重新加载到控件中。然后,您可以在页面初始化事件中每次创建标签控件,并且在这种情况下,它的 viewstate 可见属性将在回发之间保留。
Why don't you want to load the label control on every postback? With ASP.NET the entire page gets loaded with EACH postback and the view state is reloaded into the control. You can then on page init event create the label control each time and it's viewstate visible property in this case would be kept between postbacks.