質問と回答を含む HTML ページがあります。HTML ページからデータ (質問/回答) を抽出し、JavaScript オブジェクトに入れたいと考えています。
これは、私の HTML ページのクラス構造です。
- 質問ブロック
- 質問 (質問ブロックごとに 1 つの質問のみ)
- 回答(質問ごとに複数回答可能)
これは、次の構造の HTML コードです。
<div class="question-block">
<h3>Question 1</h3>
<label class="question">Name</label>
<input type="text" class="answer" />
<div class="question-block" style="margin-left:20px;">
<h4>Question 1 a</h4>
<label class="question">What is your gender?</label>
<div class="radio">
<input type="radio" class="answer" name="gender" id="radio-male" value="male">
<label for="radio-male">Male</label>
</div>
<div class="radio">
<input type="radio" class="answer" name="gender" id="radio-female" value="female">
<label for="radio-female">Female</label>
</div>
</div>
</div>
<div class="question-block">
<h3>Question 2</h3>
<label class="question">Occupation</label>
<input type="text" class="answer" />
</div>
<br />
<button id="extract" type="button">Extract HTML data</button>
<pre id="extract-div"></pre>
次のように、JavaScript でオブジェクト構造を作成したいと考えています。
{
"questions": [
{
"question": "Name",
"answers": [
{
"answer": "Kristof"
}
]
},
{
"question": "What is your gender?",
"answers": [
{
"answer": "Male"
}
]
},
{
"question": "Occupation",
"answers": [
{
"answer": "Student"
}
]
}
]
}
ネストされた「質問ブロック」(1a. あなたの性別は?) を除いて、すべてが機能します。この質問の回答も質問 1 に追加されます。
JavaScript または JQlite を使用して、現在の「質問ブロック」クラスにある回答のみを選択するにはどうすればよいですか (私は角度を使用しています)。
私の「質問ブロック」クラスを複数レベルの深さでネストできるはずです。(例のように1レベルだけではありません)
それをテストしたり、私の JavaScript コードをチェックしたりしたい場合は、ここに私のフィドルがあります: https://jsfiddle.net/aywxte23/