我正在尝试循环 div 中的输入元素,以创建对象数组
<div id="time">
<input type="text" name="from" placeholder="12:00 AM" />
<input type="text" name="to" placeholder="12:30 AM" />
<input type="text" name="from" placeholder="13:00 AM" />
<input type="text" name="to" placeholder="13:30 AM" />
</div>
我正在尝试创建以下对象数组。
unavailability: [
{ from: '12:00', to: '12:30' },
{ from: '13:00', to: '13:30' }
]
这是我到目前为止所尝试过的,但结果却截然不同。
var dataArray = []
$("#time").find('input').each(function() {
var data = {};
data[this.name] = this.value
dataArray.push(data);
});
console.log(dataArray)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="time">
<input type="text" name="from" placeholder="12:00 AM" />
<input type="text" name="to" placeholder="12:30 AM" />
<input type="text" name="from" placeholder="13:00 AM" />
<input type="text" name="to" placeholder="13:30 AM" />
</div>
JSFiddle https://jsfiddle.net/ss725ere/
您可以迭代具有 name 属性值的所有元素,如下所示from
。为了得到to
价值、用途next()
jQuery 的方法。
Use .val()
方法来获取item的值。
$('#submit').click(function() {
var data = [];
$('#time input[name="from"]').each(function() {
data.push({
from: $(this).val(),
to: $(this).next().val()
});
});
console.log(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Enter times in the below textboxes
<div id="time">
<input type="text" name="from" placeholder="12:00 AM" />
<input type="text" name="to" placeholder="12:30 AM" />
<input type="text" name="from" placeholder="13:00 AM" />
<input type="text" name="to" placeholder="13:30 AM" />
</div>
<button id="submit">Submit</button>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)