如何在运行时为标签分配值 [英] how to assign value to label at runtime

查看:82
本文介绍了如何在运行时为标签分配值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在运行时使用onkeypress事件为标签分配值.为此,我编写了以下Java脚本:

I want to assign value to label at runtime using onkeypress event. For this I wrote the following java script:

function Keypress()
{
    var keyId=document.getElementById('ctl00_ContentPlaceHolderTM_txtTitle').value;
  alert(keyId);        document.getElementById('ctl00_ContentPlaceHolderTM_lblAddTitle')=keyId;
}


此Java脚本在按键事件上起作用,但不会为标签分配值.为什么?


This java script works on key press event but not assigns a value to the label. Why?

推荐答案

尝试以下方法:

Try something along the lines of:

document.getElementById("ctl00_ContentPlaceHolderTM_lblAddTitle").innerText = keyId;


尝试一下

Try this

document.getElementById(''ctl00_ContentPlaceHolderTM_lblAddTitle'').innerHtml = keyId


问题是,当我们尝试通过javascript将值设置为标签时,起初它将接受新值,但在回发时,它将被更改为以前的值值.

但是onkeypress事件将一直有效,直到有回发.
当我们将return设为false以避免在按钮上进行回发时,该值将保持到下一次回发.

请尝试使用以下代码(它可以正常工作,但会在回发时重置):

使用以下JavaScript函数:
The issue is, when we try to set value to the label from javascript, at first it will accept the new value but on post back, it will be changed to its previous value.

But onkeypress event, it will work untill there is a post back.
When we call a return false to avoid postback on button click the value will stay untill the next postback.

Please try with the following code (It is working, but resets on postback):

Use the following JavaScript functions:
function ChangeText(retval) {
            document.getElementById("testLabel").innerText = "New Text (onclick) : Return Value - " + retval;
            return retval;
        }
        function keyPress() {
            document.getElementById("testLabel").innerText = "New Text (onkeypress)";
        }



添加以下控件以测试该功能:



Add the following controls to test the function:

<asp:Label ID="testLabel" runat="server" Text="ASP LABEL CONTROL"></asp:Label>
        <input type="button" value="HTML btn retval true" onclick="ChangeText(true);" />
        <input type="button" value="HTML btn retval false" onclick="ChangeText(false);" />
        <asp:Button ID="testButton" runat="server" Text="ASP btn retval false" OnClientClick="javascript:return ChangeText(false);" />
        <asp:Button ID="testButton2" runat="server" Text="ASP btn retval true" OnClientClick="javascript:return ChangeText(true);" />
        <asp:TextBox ID="testTextBox" runat="server" onkeypress="javascript:keyPress();"></asp:TextBox>




请在测试后随时返回并添加您的评论. :)
:thumbsup:




Please feel free to revert back after testing and add your comments on it. :)
:thumbsup:


这篇关于如何在运行时为标签分配值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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