使用 Jquery 访问隐藏字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2024165/
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
Access hiddenfield using Jquery
提问by keyboardP
I have a page that's derived from a master page. On this page, I have a hiddenfield ("hfUser"). How can I access this "hfUser" control and get/set its value using JQuery? I've tried variants of this:
我有一个源自母版页的页面。在此页面上,我有一个隐藏字段(“hfUser”)。如何使用 JQuery 访问此“hfUser”控件并获取/设置其值?我试过这样的变体:
$(document).ready(function() {
var test = $("#hfUser").val();
alert(test);
});
but test = undefined. I'm guessing I've got the selector wrong, but I don't know how to get an asp hiddenfield. Any ideas?
但测试 = 未定义。我猜我把选择器弄错了,但我不知道如何获得 asp 隐藏字段。有任何想法吗?
Thanks
谢谢
回答by Doug R
If you are using Asp.net controls, the server will mangle the control ids. It adds a bunch of extraneous control tree hierarchy information into the id. You need to reference what that acutal id is that's getting rendered, which is availble with the ClientID property on the control (hfUser.ClientID) or access your control in a different, more roundabout way, like find the controls parent, then search through its children to find your control.
如果您使用的是 Asp.net 控件,服务器将破坏控件 ID。它将一堆无关的控制树层次结构信息添加到 id 中。您需要引用正在呈现的实际 ID,这可通过控件 (hfUser.ClientID) 上的 ClientID 属性使用,或者以不同的、更迂回的方式访问您的控件,例如找到控件父级,然后搜索它的孩子找到你的控制。
If you don't have to use the asp.net HiddenField control, try just using a regular old html input.
如果您不必使用 asp.net HiddenField 控件,请尝试使用常规的旧 html 输入。
回答by Eric Burdo
ASP does like to mangle ID's. The further down the rabbit hole (or nesting controls) you go, the more ASP adds to your control ID. Throw in Master Pages, and it's yet another level or two.
ASP 确实喜欢破坏 ID。您越深入兔子洞(或嵌套控件),ASP 添加到您的控件 ID 的次数就越多。加入母版页,它又是一个或两个级别。
Another way to access server-side controls (with the runat property set), is to use the square brackets in your jQuery selector.
访问服务器端控件(使用 runat 属性集)的另一种方法是在 jQuery 选择器中使用方括号。
Like this:
像这样:
$("[id$='hidImgSource']").val()
That selects any elements whose ID has 'hidImgSource' as ending part of the name. So it will find mangled ID's.
这将选择其 ID 具有 'hidImgSource' 作为名称结尾部分的任何元素。所以它会找到损坏的 ID。
Here is a link to the jQuery Selectors pagethat explains some more options.
这是jQuery 选择器页面的链接,其中解释了更多选项。
回答by Tim Banks
If the hidden field is an ASP.NET control, check out this blog post to help you with jQuery selectors for ASP.NET controls
如果隐藏字段是 ASP.NET 控件,请查看此博客文章以帮助您使用 ASP.NET 控件的 jQuery 选择器
http://www.foliotek.com/devblog/extending-jquery-to-select-asp-controls/
http://www.foliotek.com/devblog/extending-jquery-to-select-asp-controls/
回答by Andreas
Do it like this:
像这样做:
$(document).ready(function()
{
var test = $("**#<%= hfUser.ClientID %>**").val();
alert(test);
});