使用 javascript 获取 asp.net 标签控件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8822398/
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-26 04:41:18  来源:igfitidea点击:

Get an asp.net Label control using javascript

javascriptasp.netlabels

提问by codemaster

I have a label control with in a form view that displays the sum of few textboxes. I am not able to get the id of label tb_TA_2_6 in java script.

我在表单视图中有一个标签控件,它显示几个文本框的总和。我无法在 java 脚本中获取标签 tb_TA_2_6 的 ID。

i tried

我试过

<script type ="text/jscript" language= "javascript" >
 function autosum(t1, t2) {
var sum;
var a = document.getElementById('tb_TA_2_6'); // does not work
var b = FindControl(FormView1, t2); // does not work
var c = <%= 'tb_TA_2_6'.ClientID%>; // unknown component tb_TA_2_6
var c = <%= tb_TA_2_6.ClientID%>; //The name 'tb_TA_2_6' does not exist in the current context

var num2 = $(t2);
    if (num2.textContent)
        sum = num2.textContent;
    else if (num2.innerText)
        sum = num2.innerText;
    else
        sum = num2.innerHTML;
 }

function FindControl(parentControl, strId)
    {
        var returnObject;
        for(i=0;i < parentControl.elements.length; i++)
        {
            if(parentControl.elements[i].id.indexOf(strId) >= 0)
                returnObject = parentControl.elements[i];
            else if(parentControl.elements[i].hasChildNodes())
                returnObject = FindControl(parentControl.elements[i],strId);

            if(returnObject != null) 
            {   //if object is found return
                return returnObject;
            }
        }
        return returnObject;
    }
 </script>        

but none of it seems to work, does anyone has an idea what's going on with the label with id tb_TA_2_6.

但它似乎都不起作用,有没有人知道 id 为 tb_TA_2_6 的标签发生了什么。

The form view looks like

表单视图看起来像

<asp:FormView ID="FormView1" runat="server" ClientIDMode="Static">
<ItemTemplate>
    <asp:Label ID="labelID" runat="server" Text='<%#Bind("ID") %>' Visible="false"></asp:Label>
    <table id="table1">
        <tr>
            <td>
                <span > Textbox1 </span>
            </td>
            <td>
                <asp:TextBox ID="tb_TA_2_4" onBlur="Javascript:autosum(this, '<%= tb_TA_2_6.ClientID%>');"  runat="server"  Text='<%#Bind("question6i","{0:$#,#0.00}") %>'></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                <span>6. (iii) Total Value  </span>
            </td>
            <td>
                <asp:Label ID="tb_TA_2_6" runat="server" ReadOnly="true" Text='<%#Bind("question6iii", "{0:$#,#0.00}") %>'  OnPreRender="FormView1_PreRender" ></asp:Label>
            </td>
        </tr>
    </table>
</ItemTemplate>

html rendered is like following, I removed the style information in my question.

呈现的 html 如下所示,我删除了问题中的样式信息。

<tr>

                    <td style="vertical-align: middle; width: 697px; height: 15px; border-style: solid;

                        border-color: #6699cc; border-width: 1px; border-top: 1px solid #fff;">

                        <span style="font-family: MS Sans Serif; font-size: 14px; color: #000000">6. (iii) Total

                            Value of All Benefits For Payment of Utilities </span>

                    </td>

                    <td class="alignright" style="vertical-align: top; width: 157px; height: 15px; border-style: solid;

                        border-color: #6699cc; border-width: 1px; border-left: 1px solid #fff; border-top: 1px solid #fff;">

                        <span id="ctl00_cph_Main_FormView1_tb_TA_2_6" ReadOnly="true" style="font-size:12pt;">.00</span>

                    </td>

                </tr>

回答by Kelsey

Labelcontrols render as a spanin the HTML.

Label控件span在 HTML 中呈现为 a 。

To access it you need to get it's ClientID.

要访问它,您需要获取它的ClientID.

You can change your javascript to:

您可以将 javascript 更改为:

var a = document.getElementById('<%= tb_TA_2_6.ClientID %>');

Your var cexample had the Labelcontrol name wrapped in quotes so that is why it was failing.

您的var c示例将Label控件名称用引号括起来,这就是它失败的原因。

You could also set the ClientIDModeto staticfor you page if you want the controls to render their IDs exactly how you specify them. Then your original getElementByIdwill work as expected without having to get the rendered ClientID.

您还可以设置ClientIDModestatic,如果你想控制来呈现其ID究竟如何指定他们为你的页面。然后您的原件getElementById将按预期工作,而无需获得渲染的ClientID.

See MSDNfor ClientIDModeinfo.

请参阅MSDN的ClientIDMode信息。

EDIT:If your controls are part of a container template you need to access the control differently by getting the container control and then doing a FindControlfrom it.

编辑:如果您的控件是容器模板的一部分,您需要通过获取容器控件然后FindControl从中执行 a来以不同的方式访问控件。

var a = document.getElementById('<%= FormView1.FindControl("tb_TA_2_6").ClientID %>');

回答by Stefan

As we can see your ASP.NET Label with ID "tb_TA_2_6" renders as a spanelement with ID "ctl00_cph_Main_FormView1_tb_TA_2_6".

正如我们所看到的,您的 ID 为“tb_TA_2_6”的 ASP.NET 标签呈现为 ID 为“ctl00_cph_Main_FormView1_tb_TA_2_6”的span元素。

document.getElementById('ctl00_cph_Main_FormView1_tb_TA_2_6')would then select the element.

document.getElementById('ctl00_cph_Main_FormView1_tb_TA_2_6')然后将选择该元素。

You should also know that your label is created within a ItemTemplatein your FormViewand that it most likely renders multiple items. This is why you can′t access tb_TA_2_6.ClientID.

您还应该知道您的标签是ItemTemplate在您的a中创建的,FormView并且它很可能呈现多个项目。这就是您无法访问的原因tb_TA_2_6.ClientID

Now, which item do you want your Javascipt to select the spanelement from?

现在,您希望 Javasciptspan从哪个项目中选择元素?

UPDATE

更新

It looks like you′re trying to create a table and summarize some value from each row. Here we go;

看起来您正在尝试创建一个表格并总结每一行的一些值。开始了;

ASP.NET UserControl

ASP.NET 用户控件

<table id="myTable">
<asp:FormView ID="FormView1" runat="server">
<ItemTemplate>
    <tr>
        <td><span>Textbox1</span></td>
        <td><asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("question6i", "{0:$#,#0.00}") %>' class="myValue" /></td>
    </tr>
</ItemTemplate>
</asp:FormView>

    <tr>
        <td><span>6. (iii) Total Value</span></td>
        <td><asp:Label ID="TextBox1SumLabel" runat="server" Text='<%# Bind("question6iii", "{0:$#,#0.00}") class="sum" %>' /></td>
    </tr>
</table>

HTML, example of expected ouput

HTML, 预期输出示例

<table id="myTable" class="styledTable">
    <tr>
        <td><span>Textbox1</span></td>
        <td><input type="text" id="SomeGeneratedClientID_00" class="myValue" Value='60.00' /></td>
    </tr>
    <tr>
        <td><span>Textbox1</span></td>
        <td><input type="text" id="SomeGeneratedClientID_01" class="myValue" Value='40.00' /></td>
    </tr>

    <tr>
        <td><span>6. (iii) Total Value</span></td>
        <td><span ID="ctl00_cph_Main_TextBox1SumLabel" class="sum">100.00</span></td>
    </tr>
</table>

Javascript, jQuery

Javascript, jQuery

$(document).ready(function() {

    // Bind the change event to all ".myValue" elements
    $('#myTable .myValue').change(function() {
        // Find parent table element
        var $table = $(this).closest('table');

        // Update summary
        sumTableValues($table);
    });

});

var sumTableValues = function($table) {
    var sum = 0;

    // Iterate through all .myValue elements
    $table.find('.myValue').each(function(index) {
        console.log(index, $(this).val()); // DEBUG
        // NOTE: Need to make sure the value is a number

        // Add the value to the sum
        sum += Number($(this).val());
    });

    console.log('sum', sum); // DEBUG

    // Update the sum
    $table.find('tr:last .sum').text(sum);
    //$('<%= TextBox1SumLabel.ClientID %>').text(sum);  
};

Created a demofor you to play around with, really hope this helps you in any way.

创建了一个演示供您玩,真的希望这对您有所帮助。