获取Jquery中隐藏字段的值?

5
我有以下HTML代码。
<input type="hidden" name="conf1" value="7th IEEE/IFIP International Conference on Embedded and Ubiquitous Computing (EUC-09)">
    <input type="hidden" name="conf2" value="IEEE International Symposium on Parallel and Distributed Processsing with Applications">
    <input type="hidden" name="conf3" value="jkhga">
    <input type="hidden" name="conf4" value="test">
    <input type="hidden" name="conf5" value="The 3rd International Conference on Adaptive Business Information Systems (ABIS'09)">

    <input type="text" name="published">

我正在尝试使用jQuery将隐藏字段的值获取到一个数组中。这是我的尝试:

 var conferences = new Array();

        conferences[0] = $('#conf1').val();
        conferences[1] =$("[name='conf2']").val();
        conferences[2] =$("[name='conf3']").val();
        conferences[3] = $("[name='conf4']").val();
        conferences[4] =$("[name='conf5']").val();     

有人可以指导我如何读取它们吗?
先行致谢
迪恩

6个回答

10
如果你将使用jQuery,你可以这样做:
var array = $('input:hidden').map(function() {
    return this.value;
}).get();

.map() 迭代集合,并将返回值放入 jQuery 对象中。

.get() 从 jQuery 对象中检索数组。


3
var conferences = [];

$('input:hidden[name^="conf"]').each(function() {
    conferences.push($(this).val());
});

3
var array = $.map($('input:hidden'),function(i) {
    return i.value;
});

这将为array分配值数组,比使用$(selector).map()略少冗长,后者返回一个jQuery对象,您需要调用get()才能返回一个数组。

演示在这里


1
var conferences = new Array();    // object Array

var conferencesVal = new Array(); // string Array

$("[type=hidden]").each(function(i,e){

   // object array  =>altarnatif method
   conferences.push( {name:$(this).attr("id"),value: $(this).val()});

   //string array
   conferencesVal[i]=  $(this).val();

})

0

尝试下面的代码。

$(...).attr('value');  

.attr(...):只在创建 HTML 时获取对象的值。
.val():获取对象的属性值,该值可以多次更改。


请考虑编辑您的答案,以解释为什么.val()无效而.attr()有效,这样人们就可以更好地理解问题及其适用范围。 - Djizeus

0

在我看来你的代码已经很好了,只是缺少#conf1。一切似乎都写得正确,可以通过conferences[0]conferences[1]等轻松访问数组。

您可能可以使用jQuery技巧来清理它,但如果您知道您只会有5个会议,那么您所拥有的功能就足够了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接