javascript 如何使用 JScript 设置按钮的文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6900398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 22:16:23  来源:igfitidea点击:

How to set the text of a button using JScript?

javascriptasp.net

提问by Brian Hooper

I'm trying to set the text on a button in a JScript function. I am using a JScript function like this...

我正在尝试在 JScript 函数中的按钮上设置文本。我正在使用这样的 JScript 函数...

    function myfunction(sender, eventArgs)
    {
        wanted_text = window.source_text_field.get_displayText();

        if (document.getElementById("my_span_element") != null)
        {
            document.getElementById("my_span_element").innerText = wanted_text;
        }

        if (document.getElementById("my_button") != null)
        {
            document.getElementById("my_button").text = wanted_text;
        }

    }

where the controls concerned are define like this...

所涉及的控件是这样定义的......

    <span id="my_span_element" class="some_class"></span>

    <asp:Button id="my_button"
                runat="server"
                class="some_other_class"
                text=""
                Width="48"
                Height="25"
                onclick="do_foo"/>

The text in the span element is set correctly but the button is unaffected. I've also tried innerText, Value, Text, and also attempted to use the answer to this questionbut to no avail.

span 元素中的文本设置正确,但按钮不受影响。我也试过innerTextValueText,还企图利用回答这个问题,但没有成功。

Can anyone see what I have overlooked?

谁能看到我忽略了什么?

回答by The Mask

Change the .valueattribute of button:

更改.value按钮的属性:

document.getElementById("my_button").value = "new value";

回答by SLaks

ASP.Net generates its own IDs for server controls.

ASP.Net 为服务器控件生成自己的 ID。

You need to write <%= my_button.ClientID %>to get this generated ID.

您需要编写<%= my_button.ClientID %>以获取此生成的 ID。

回答by igorti

There are 2 problems here:

这里有2个问题:

First: you use wrong attribute - should be "value", instead of "text"

第一:您使用了错误的属性 - 应该是“值”,而不是“文本”

Second: document.getElementById("my_button")will not work because ASP.NET assigns it's own ids to controls. If you take a look at generated markup you will notice that id of the element is completely different.

第二:document.getElementById("my_button")不会工作,因为 ASP.NET 将它自己的 id 分配给控件。如果您查看生成的标记,您会注意到元素的 id 完全不同。

If your javascript is inside of the same .aspx page as <asp:button />control, you can do like this:

如果您的 javascript 位于与<asp:button />控件相同的 .aspx 页面内,您可以这样做:

document.getElementById("<%= my_button.ClientID %>").value = "some text";