如何在ASP.net中将Javascript与动态控件一起使用 [英] How to use Javascript with Dynamic Controls in ASP.net

查看:108
本文介绍了如何在ASP.net中将Javascript与动态控件一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我想将JavaScript与动态控件配合使用,
但问题javascript方法无法在页面中看到动态控件,它给我以下错误:

document.getElementById(id)为null或初始化一个对象

我将控件的ID正确传递给javascript方法,因为我使用alert来显示ID及其正确.
并且javascript方法中的所有代码都可以正常工作,除了这一行
document.getElementById(id)

这是我的方法:

Hi,

I want to use javascript with dynamic controls,
but the problem javascript method cannot see the dynamic control in the page, it give me error that:

document.getElementById(id) is null or nit an object

i pass the id of control to javascript method correctly, as i use alert to show the id and it right.
and all code in javascript method work right except this line
document.getElementById(id)

this is my method:

function SpecificMethod(id)
{
   // some code here work fine
  
  alert(id);  // give me right id 
  document.getElementById(id).disabled =true;  // give error
}



这是动态创建控件的代码:



and this is the code which create the control dynamically:

protected void Page_Load(object sender, EventArgs e)
    {
        LinkButton lbtnMyLink = new LinkButton();

        lbtnMyLink.Text = "Hello world";
        lbtnMyLink.ID = "lbtnMyLink_1";
        
        lbtnMyLink.OnClientClick = "SpecificMethod(" + lbtnMyLink.ClientID + ");return false";
        
        divTest.Controls.Add(lbtnMyLink);
    }

推荐答案

仅仅是因为获得ID并不意味着它是正确的.调试脚本,查看源以验证您要使用的DOM元素的实际ID.

由于您没有提供关于此控件的含义或用法的任何线索,因此请记住ASP.NET会弄乱该名称.您在标记中分配的ID可能与浏览器中呈现的ID不一致.
Just because you get an id doesn''t mean it is correct. Debug you script, look at the source to verify the actual id for the DOM element you are trying to use.

Since you have given us no clue as to what this control is or how it is used, remember ASP.NET will mangle the name. The id you assign in the markup may not be the same as what is rendered in the browser.


服务器端ID和客户端端ID不一致.尝试这样的事情:
The server-side ID and the client-side ID are not the same. Try something like this:
document.getElementById("<%= serverSideControl.ClientID %>").disabled = true;



如果要查看示例客户端ID,只需运行Web应用程序,然后在IE中右键单击并选择查看源代码".这将向您显示ASP.Net渲染到的HTML.

另外,请勿对您看到的客户端ID进行硬编码...客户端ID可能会因多种因素而发生变化.只需使用ClientID属性即可动态获取客户端ID.



If you want to see an example client-side ID, just run your web application and right-click in IE and select "view source". That will show you the HTML that the ASP.Net renders to.

Also, do NOT hardcode the client-side ID you see... the client-side ID can change depending on a number of factors. Just use the ClientID property to get the client-side ID dynamically.


这篇关于如何在ASP.net中将Javascript与动态控件一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆