【发布时间】:2021-01-16 02:26:15
【问题描述】:
我有多个 <div> 元素,它们有 3 个共同点(<h3>、<textarea>、<img>)。单击按钮后,我需要获得 JSON 结果(在下面共享)。
这是我尝试过的,但我无法转换为 JSON,但我能够将其转换为单独的数组。
function get_json() {
var groups = Array.from(document.querySelectorAll(".StackedList"));
var imgs = groups.map(function(group) {
return Array.from(group.querySelectorAll("img")).map(function(item) {
return new URL(item.src).pathname.substring(1);
});
});
var desc = groups.map(function(group) {
return Array.from(group.querySelectorAll("textarea")).map(function(item) {
return item.value
});
});
var h3text = groups.map(function(group) {
return Array.from(group.querySelectorAll("h3")).map(function(item) {
return item.innerText
});
});
alert(imgs + desc + h3text)
return imgs, desc, h3text
}
<div class="StackedList" id="group1">
<h3 id="c1" style="display:inline" contenteditable="true">Item 1</h3>
<textarea id="desc1" placeholder="Enter the description" name="w3review"></textarea>
<img class="draggable" src="http://localhost:99/10.jpg" />
<img class="draggable" src="http://localhost:99/11.jpg" />
<img class="draggable" src="http://localhost:99/12.jpg" />
</div>
<div class="StackedList" id="group2">
<h3 id="c2" style="display:inline" contenteditable="true">Item 2</h3>
<textarea id="desc2" placeholder="Enter the description" name="w3review"></textarea>
<img class="draggable" src="http://localhost:99/8.jpg" />
<img class="draggable" src="http://localhost:99/7.jpg" />
<img class="draggable" src="http://localhost:99/2.jpg" />
</div>
<div class="StackedList" id="group3">
<h3 id="c3" style="display:inline" contenteditable="true">Item 3</h3>
<textarea id="desc3" placeholder="Enter the description" name="w3review"></textarea>
<img class="draggable" src="http://localhost:99/1.jpg" />
</div>
<input type="button" value="Get json" onclick="get_json()">
预期输出
我需要在单击按钮时获取 JSON。
{
"Item 1": {
"descrption": "Entered text value",
"images": ["10.jpg", "11.jpg", "12.jpg"]
},
"Item 2": {
"descrption": "Entered text value",
"images": ["8.jpg", "7.jpg", "2.jpg"]
},
"Item 3": {
"descrption": "Entered text value",
"images": ["1.jpg"]
}
}
【问题讨论】:
-
什么是
Item 1 -
第1项
h3元素文本
标签: javascript