请在下面的html代码中找到:
<table class="table table-bordered queTable" id="qustionTbl">
<thead>
<tr>
<th width="60px">Sr No</th>
<th>Enter Question</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<b>Q.1</b>
</td>
<td>
<div class="QuestionDiv">
<div class="row ">
<div class="col-sm-10 col-xs-10 col-md-10">
<input class="form-control questionTxt" placeholder="Question" type="text">
</div>
</div>
<div class="subQuestionDiv">
<div class="row">
<div class="col-sm-10 col-xs-10 col-md-10">
<input class="form-control subQuestionTxt" placeholder="Question" type="text">
</div>
</div>
</div>
<div class="subQuestionDiv">
<div class="row">
<div class="col-sm-10 col-xs-10 col-md-10">
<input class="form-control subQuestionTxt" placeholder="Question" type="text">
</div>
</div>
</div>
<div class="subQuestionDiv">
<div class="row">
<div class="col-sm-10 col-xs-10 col-md-10">
<input class="form-control subQuestionTxt" placeholder="Question" type="text">
</div>
</div>
</div>
</div>
</td>
</tr>
</tbody>
</table>
在上面的HTML表中,我想通过Jquery初始化所有行以从每个行中获取
.QuestionDiv
,并从每个.QuestionDiv中获取所有.subQuestionDiv
。我写了下面的jQuery代码来做到这一点。我从行中获取
.QuestionDiv
,但是我没有从.subQuestionDiv
对象中获取所有.QuestionDiv
。请帮忙。jQuery代码:
$('#qustionTbl').find('tr').each(function (i, el) {
question={}
subQuestionList=[]
var $tds = $(this).find('td')
questionDivObj = $tds.eq(1).find('.QuestionDiv')
questionTxt=$(questionDivObj).find('.questionTxt').val()
question['question']=questionTxt;
// HERE IS THE PROBLEM, HOW TO GET ALL .subQuestionDiv DIV
// FROM questionDivObj
$(".subQuestionDiv").each( function() {
subQuestionTxt=$(this).find('.subQuestionTxt').val()
subQuestionList.push({'subQuestion':subQuestionTxt});
});
question['subQuestions']=subQuestionList
questionsList.push(question)
});
});
最佳答案
您只需要在jQuery选择器中添加“上下文”即可:
$(".subQuestionDiv", questionDivObj).each(...)
在您的代码上下文中:
$('#qustionTbl').find('tr').each(function (i, el) {
question={}
subQuestionList=[]
var $tds = $(this).find('td')
questionDivObj = $tds.eq(1).find('.QuestionDiv')
questionTxt=$(questionDivObj).find('.questionTxt').val()
question['question']=questionTxt;
// add context to this selector, finds within this question div $(".subQuestionDiv", questionDivObj).each( function() {
subQuestionTxt=$(this).find('.subQuestionTxt').val()
subQuestionList.push({'subQuestion':subQuestionTxt});
});
question['subQuestions']=subQuestionList
questionsList.push(question)
});