gpt4 book ai didi

javascript - 如何从任何 jquery 对象中获取具有相同类名的所有元素?

转载 作者:行者123 更新时间:2023-11-30 21:15:06 26 4
gpt4 key购买 nike

请在下面找到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 表中,我想迭代所有行以从每一行获取 .QuestionDiv 并通过 Jquery 从每个 .QuestionDiv 获取所有 .subQuestionDiv。我已经编写了以下 jquery 代码来获取它。我正在从行中获取 .QuestionDiv,但我不知道如何从 .QuestionDiv 对象获取所有 .subQuestionDiv。请帮忙。

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)

});

关于javascript - 如何从任何 jquery 对象中获取具有相同类名的所有元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45761650/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com