|
 |
|
การ loop each div เพื่อหา ค่าของ elements โดยค่า elements นั้นก็เป็น arrays เช่นกัน (มีตัวอย่าง) |
|
 |
|
|
 |
 |
|
อธิบายใหม่ได้มั้ยครับ อ่าน 3 รอบยังไม่เข้าใจ
|
 |
 |
 |
 |
Date :
2020-08-04 17:32:58 |
By :
Genesis™ |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
 |
|
|
 |
 |
|
Code (JavaScript)
var Items_sub = [];
$(".parent").each( (i,e)=>{
$(e).find("input").each( (j, inp)=>{
Items_sub[i][inp.name] = inp.value;
});
});
|
ประวัติการแก้ไข 2020-08-04 17:34:13 2020-08-04 17:35:51
 |
 |
 |
 |
Date :
2020-08-04 17:33:44 |
By :
Chaidhanan |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
 |
|
|
 |
 |
|
Code (JavaScript)
<!DOCTYPE html>
<html>
<body>
<div class="parent" data-type="type1">
<input name="sub[0]" data-date="2020-08-04" value="1">
<input name="sub[1]" data-date="2020-08-05" value="2">
<input name="sub[1]" data-date="2020-08-06"value="3">
</div>
<div class="parent" data-type="type2">
<input name="sub[0]" data-date="2020-08-04" value="4">
<input name="sub[1]" data-date="2020-08-05" value="5">
<input name="sub[1]" data-date="2020-08-06"value="6">
</div>
<div class="parent" data-type="type3">
<input name="sub[0]" data-date="2020-08-04" value="7">
<input name="sub[1]" data-date="2020-08-05" value="8">
<input name="sub[1]" data-date="2020-08-06"value="9">
</div>
<!-- ระวัง name ซ้ำกัน...จะส่งผลให้ได้รับข้อมูลเพี้ยนเมื่อใช้ AJAX POST -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
var Items_parent = []; // ประกาศเป็น array แต่หลังจากใช้ name index จะแปลงร่างเป็น object
$(".parent").each(function(i, e){ // element ใส่เป็น parameter 2
var Items_sub = {};
$(e).find("input[name^='sub']").each(function () { // เอาเฉพาะ input ของแต่ละ type
var val = $(this).val();
var dateData = $(this).attr('data-date');
Items_sub[dateData] = val;
});
Items_parent[$(this).attr('data-type')] = Items_sub; // อาร์เรย์ Items_parent เปลี่ยนเป็น object
});
console.log(Items_parent);
// PhrayaDev@2020
</script>
</body>
</html>
https://www.w3schools.com/code/tryit.asp?filename=GHG13B8FTO3W
ถ้าสามารถใช้ ES6(ไม่แคร์ IE) ทำตาม คห.2
แต่ต้องเพิ่มอีกบรรทัด คือ ประกาศ array elements ในมิติที่ 1 ให้เป็น array ก่อน
ไม่งั้นจะเจอ undefined ตอนถ่ายค่ามิติ 2
|
 |
 |
 |
 |
Date :
2020-08-05 15:17:12 |
By :
PhrayaDev |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
|
|
|

|
Load balance : Server 05
|