C# document.getElementById('id').value 在 ASP.net javascript 函数中失败

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

document.getElementById('id').value failing in ASP.net javascript function

javascriptc#asp.netgetelementbyidrunatserver

提问by todd.pund

Hidden fields:

隐藏字段:

<input type="hidden" id="hidOrg1"  runat="server" value="" />
<input type="hidden" id="hidBT" runat="server" value="" />

javascript function:

javascript函数:

function doGetWave(obj) {
    //debugger
    var brk = document.getElementById('hidBT').value;
    //var brkId = document.getElementById('hidBI').value;
    var org = document.getElementById('hidOrg1').value;
    session = obj.options[obj.selectedIndex].value;
    sWaveText = obj.options[obj.selectedIndex].text;    
    if (brk == "") {
        window.location.href = "url.aspx?multiple=" + org + "&wave=" + sWaveText + "&strORGId=multiple";
    }
    else {
        window.location.href = "url.aspx?multiple=" + org + "&wave=" + sWaveText + "&BRKType=" + brk + "&strORGId=multiple";
    }
}

codebehind:

代码隐藏:

protected void Page_Load(object sender, EventArgs e)
{
    hidOrg1.Value = strOrgId;
    hidBT.Value = "";
}

The javascript function errors out with "Object Expected" at the var brk = ... and I cannot figure out where it is going wrong. Pulling my hair out! :(

javascript 函数在 var brk = ... 处出现“Object Expected”错误,我不知道哪里出错了。拉我头发!:(

采纳答案by James Hill

When you place runat="server"in an standard HTML tag, ASP.Net mangles the ID to ensure that it's unique (just like it does with its own controls). You need to access the element using the ID that ASP.Net assigned. Try this:

当您放置runat="server"在标准 HTML 标记中时,ASP.Net 会修改 ID 以确保它是唯一的(就像它对自己的控件所做的一样)。您需要使用 ASP.Net 分配的 ID 访问该元素。尝试这个:

var brk = document.getElementById('<%= hidBT.ClientID %>').value;
var org = document.getElementById('<%= hidOrg1.ClientID %>').value;

Additional Information

附加信息

If you're using the 4.0 framework, you can change this behavior at the element, page, or application level. Check out this linkfor a decent little tutorial. If you choose to set the ClientIdModeto Static, you can access your elements by the ID's that you originally assigned (they will not be changed).

如果您使用的是 4.0 框架,则可以在元素、页面或应用程序级别更改此行为。查看此链接以获得一个不错的小教程。如果您选择将 设置ClientIdModeStatic,您可以通过您最初分配的 ID 访问您的元素(它们不会更改)。