簡體   English   中英

jQuery,將多個值附加到一個隱藏的輸入

[英]jquery, append multiple values to one input hidden

我有以下變量

var $pk3s_c = $('<input id = query_form_tbl_info_'+query_index +'_pk3ss[] name =query_form[tbl_info]['+query_index+'][pk3ss][] type = hidden></input>');

和一個數組

var pk3s = opts[tbl]["cols"];

在遍歷數組的過程中,我想將數組的元素附加到$pk3s_c

  $.each(pk3s, function(i,pk3){
  $pk3s_c.attr('value',pk3);
  })

上面的代碼不起作用,它向我顯示我僅附加了pk3的最后一個元素,而不是全部。 如何將p3ks的每個元素附加到隱藏的輸入中?

為了提高可讀性,我會將參數作為參數傳遞給jQuery函數

看起來像

 var values = ['argument1', 'argument2', 'argument3']; var query_index = 43; var jqueryAttributes = { id: 'query_form_tbl_info_' + query_index + '_pk3ss[]', name: 'query_form[tbl_info][' + query_index + '][pk3ss][]', type: 'hidden', value: JSON.stringify(values) // if your server don't support HTML encoding, use the one below instead // value: "['"+values.join("','")+"']" }; var $newElement = $('<input/>', jqueryAttributes); alert('you element would look like : ' + $newElement[0].outerHTML); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> 

如果不將數組轉換為字符串,就不會將其放入字符串字段。

JSON格式對此非常有用

// convert the array to a string
var myString = JSON.stringify(myArray);

// put the string into the field as it's value
$('input').val(myString);

Javascript可以解釋生成的字符串,服務器端語言可以輕松地將其從字符串轉換為他們可以理解的數組值(有關,請參見phpruby

這是一個jsfiddle中的示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM