我正在尝试将对象推入Array,这并不是没有发生,它返回空对象数组。喜欢这个[{},{}],不显示值。
这是我的JS代码。
function sendFormValues() {
var result_arr = [];
var kids = $(".panel-group").map(function() {
kidName = $(this).find('.kid-name').text();
kidAge = $(this).find('.kid-age').text();
if (kidName || kidAge) {
var obj = {
kidName: kidName,
kidAge: kidAge
};
console.log(obj); //** Here object print correctly.**
result_arr.push(obj);
console.log(result_arr); //** here showing empty object. line []**/
}
return result_arr;
}).get();
console.log(result_arr); /** // printing like [{},{}]**/
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="panel-group">
< div class=" panel-heading " >
<a class="kid-name ">Some dynamic value</a>
<a class="kid-age ">Some dynamic value</a>
</div >
</div >
<a href="javascript() " onclick="sendFormValues() ">Send value</a>
有人可以在这里帮助我在做什么吗?
谢谢。
答案 0 :(得分:0)
function sendFormValues() {
var result_arr = [];
var kids = $(".panel-group>.panel-heading").each(function() {
var kidName = $(this).find('.kid-name').text();
var kidAge = $(this).find('.kid-age').text();
var obj = {
kidName: kidName || '',
kidAge: kidAge || ''
};
result_arr.push(obj);
});
console.log(result_arr);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="panel-group">
<div class="panel-heading">
<a class="kid-name ">Some dynamic value1</a>
<a class="kid-age ">Some dynamic value1</a>
</div>
<div class="panel-heading">
<a class="kid-name ">Some dynamic value2</a>
<a class="kid-age ">Some dynamic value2</a>
</div>
<a href="javascript:;" onclick="sendFormValues() ">Send value</a>
</div>
看到这个。
答案 1 :(得分:0)
我将值分别推送到列表中,并且按您期望的结果将其放入两个数组[{},{}]
<html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
function sendFormValues() {
var result_arr = [];
var kids = $(".panel-group").map(function() {
kidName = $(this).find('.kid-name').text();
kidAge = $(this).find('.kid-age').text();
if (kidName || kidAge) {
//console.log(obj); // Here object print correctly.**
result_arr.push({
kidName: kidName
});
result_arr.push({
kidAge: kidAge
});
console.log(result_arr); // here showing empty object. line []**
}
return result_arr;
}).get();
console.log("result", result_arr); // printing like [{},{}]**
}
</script>
<body>
<div class="panel-group">
<div class="panel-heading">
<a class="kid-name ">Some dynamic value</a>
<a class="kid-age ">Some dynamic value</a>
</div>
</div>
<a href="#" onclick="sendFormValues()">Send value</a>
</body>
</html>
<!-- end snippet -->