更新时间:2023-02-11 21:18:21
hidAnswer = selected.value;
那个需要:
That needs to be:
document.getElementById("hidAnswer").value = selected.value;
因为它看,你只是将值赋给未声明的局部变量。
As it stands, you're just assigning the value to an un-declared local variable.
HiddenField
是一个ASP.NET服务器控制
,因此您无法通过直接引用其ID来访问它们。要在JavaScript
中访问它们,您需要使用函数.document.getElementById 并传递控件的ID。
例如:
HiddenField
is an ASP.NETServer Control
, so you can't access them by directly referencing their ID. To access them inJavaScript
, you would need to use the function document.getElementById and pass along the ID of the control.
For example:
document.getElementById('<%=hidAnswer.ClientID%>').value = 'set whatever value here';
请注意,我们使用的是 ClientID
,而不是 HiddenField
的 ID
,原因是因为ASP.NET会在标记中呈现不同的ID,尤其是当您的控件嵌套在 NamingContainer
中时。所以实际ID看起来像 clt0_clt1_hidAnwser
。
在.NET 4.x中,引入了 ClientMode
属性以避免呈现自动生成的ID请参阅: Control.ClientIDMode属性(System.Web) .UI)| Microsoft Docs [ ^ ]
因此,如果设置 ClientMode =Static
对于服务器控件,那么你可以安全地使用这样的东西来访问控件:
Note that we are using the ClientID
, instead of the ID
of the HiddenField
, the reason for this is because ASP.NET will render a different ID in the markup especially if your control is nested within a NamingContainer
. So the actual ID could look something like clt0_clt1_hidAnwser
.
In .NET 4.x, The ClientMode
property was introduced to avoid the autogenerated ids being rendered See: Control.ClientIDMode Property (System.Web.UI) | Microsoft Docs[^]
So if you set ClientMode= "Static"
for a Server Control, then you can safely use something like this to access the control:
document.getElementById('hidAnswer').value = 'set whatever value here';