问题
Look at my code, I am trying to combine all value from the jquery.each
to a string like this ok,good, and then passed to ajax value. Appreciate. or array('ok','good')
acceptable also
var global = {
"44":["onset","frequency"],
"45":["onset"]
};
var $val = global[44];
jQuery.each( $val, function( key ,value) {
var value = $('#'+value).val();
});
var $combine = ;//not sure how to combine all value like this (ok,good), or array(ok,good) acceptable also
var data= {
action: 'check_first',
AjaxFrontNonce : ajax_csky.AjaxFrontNonce,
combine : $combine
}
<input type="hidden" id="onset" value="ok">
<input type="hidden" id="frequency" value="good">
回答1:
Try this working snippet
var global = {
"44": ["onset", "frequency"],
"45": ["onset"]
};
var $val = global[44];
var arr = [];
$.each($val, function(key, val) {
var value = $('#' + val).val();
arr.push(value);
});
var $combine = arr; //not sure how to combine all value like this (ok,good), or array(ok,good) acceptable also
console.log($combine);
var data = {
action: 'check_first',
//AjaxFrontNonce : ajax_csky.AjaxFrontNonce, not defiend
combine: $combine
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" id="onset" value="ok">
<input type="hidden" id="frequency" value="good">
回答2:
Try this:
var global = {
"44":["onset","frequency"],
"45":["onset"]
};
var $val = global[44];
var values = [];
jQuery.each( $val, function( key ,value) {
values.push($('#'+value).val());
});
var $combine = '(' + values.join(',') + ')';
console.log($combine);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" id="onset" value="ok">
<input type="hidden" id="frequency" value="good">
回答3:
You can use $.map to go over all of the items and return the value for each element.
There is an example of both Array
and String
values, you can use whichever works better for you.
var global = {
"44":["onset","frequency"],
"45":["onset"]
};
var $val = global[44];
combinedAr = $.map($val, function(val) {
return $('#'+val).val();
});
combinedStr = combinedAr.join(",");
var data= {
action: 'check_first',
AjaxFrontNonce : ajax_csky.AjaxFrontNonce,
combine : combinedStr
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" id="onset" value="ok">
<input type="hidden" id="frequency" value="good">
来源:https://stackoverflow.com/questions/38807704/trying-to-combine-all-value-from-jquery-each-function