简体   繁体   English

将ASP.NET元素传递给JavaScript函数

[英]Passing ASP.NET Elements to JavaScript Functions

I have created the following text-box and label: 我创建了以下文本框和标签:

<asp:TextBox ID="MyTextBox" runat="server"/>
<asp:Label   ID="MyLabel"   runat="server"/>

Moreover, I have created the following JavaScript function: 而且,我创建了以下JavaScript函数:

function characterLimit(myTextBox, myLabel)
{
    myLabel.innerHTML = myTextBox.value.length + '/' + myTextBox.maxLength;
}

Finally, in the code-behind, I have performed the following: 最后,在代码隐藏中,我执行了以下操作:

TextBox1.Attributes.Add("OnKeyUp", "characterLimit(MyTextBox, MyLabel);");

characterLimit() gets called. characterLimit()被调用。 However, nothing happens; 然而,没有任何反应; it is as though I am passing MyTextBox and MyLabel incorrectly (above). 就好像我错误地传递了MyTextBoxMyLabel (上图)。 What is the correct way of doing this? 这样做的正确方法是什么?

Use the ClientID property. 使用ClientID属性。 This will help in the case you start using MasterPages , which changes the controls IDs . 这将有助于您开始使用MasterPages ,它会更改控件IDs

But, in this specific case, I guess it's just about sticking quotes around the IDs when sending as parameters. 但是,在这种特定情况下,我猜这只是在作​​为参数发送时粘贴IDs周围的引号。

TextBox1.Attributes.Add("OnKeyUp", "characterLimit('" + MyTextBox.ClientID + "','" +  MyLabel.ClientID + "');");

Following a suggestion in the comments, you should also slightly change your Javascript code: 根据评论中的建议,您还应该稍微更改您的Javascript代码:

function characterLimit(myTextBox, myLabel)
{
    document.getElementById(myLabel).innerHTML = myTextBox.value.length + '/' + document.getElementById(myTextBox).maxLength;
}

And, just as a tip, have you tried jQuery yet? 而且,就像一个提示,你尝试过jQuery了吗?

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

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