我正在尝试通过选择options
获取表question-picker
:
我这样做了:
$(document).ready(function() {
var question_container = $('.question-picker option[value="1"]').parent();
console.log(question_container);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card question">
<div class="card-body">
<div class="row">
<div class="col-xs-12 col-sm-12">
<div class="form-group">
<label for="questions" class="control-label">Question</label>
<select class="form-control question-picker required" data-max-options="1"><optgroup label="health"><option value="1">How old are you?</option><option value="2">What is your name?</option></optgroup><optgroup label="family"><option value="1">How old are your?</optgroup></select>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-12">
<div class="form-group">
<table class="table options">
<thead>
<tr>
<td><label>Option</label></td>
<td><label>Related question</label></td>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
</div>
</div>
问题是我得到了optgroup而不是表父级。 这是FIDDLE。
答案 0 :(得分:1)
您可以使用.closest()
对于集合中的每个元素,通过测试元素本身并遍历DOM树中的祖先,获得与选择器匹配的第一个元素。
获取匹配的元素集中每个元素的紧随其后的同级元素。如果提供了选择器,则只有与该选择器匹配时,它才会检索下一个同级。
获取当前匹配元素集中每个元素的后代,并通过选择器,jQuery对象或元素进行过滤。
$(document).ready(function() {
var question_container = $('.question-picker option[value="1"]').closest('.row').next().find('table.options');
console.log('Length:',question_container.length); //1
console.log('Tag Name:',question_container[0].tagName); //TABLE
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card question">
<div class="card-body">
<div class="row">
<div class="col-xs-12 col-sm-12">
<div class="form-group">
<label for="questions" class="control-label">Question</label>
<select class="form-control question-picker required" data-max-options="1"><optgroup label="health"><option value="1">How old are you?</option><option value="2">What is your name?</option></optgroup><optgroup label="family"><option value="1">How old are your?</optgroup></select>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-12">
<div class="form-group">
<table class="table options">
<thead>
<tr>
<td><label>Option</label></td>
<td><label>Related question</label></td>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
</div>
</div>
答案 1 :(得分:1)
尝试一下:
var question_container = $('.question-picker').closest("div[class='row']").next().find("table")