请在下面找到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)
});
});
答案 0 :(得分:1)
您只需要将“context”添加到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)
});
答案 1 :(得分:0)
发表评论后,我相信$(questionDivObj).children(".subQuestionDiv")
会有效。它返回与questionDivObj
匹配的".subQuestionDiv"
子项的所有元素的列表。
答案 2 :(得分:0)
试试这个:
$(questionDivObj).find(".subQuestionDiv").each( function(i,elm) {
subQuestionTxt=$(this).eq(i).find('.subQuestionTxt').val()
subQuestionList.eq(i).push({'subQuestion':subQuestionTxt});
});