我想提醒单击该框的容器的选定vat
选项。但是我得到了一个未定义的结果:
$(document).on('click', '.box', function(event) {
var result = $(this).closest('.container').find('.vat').find("option:selected").val();
alert(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr class='container'>
<td>
<div class="box">box1</div>
</td>
<td>
<select class='vat'>
<option value='0'>0 %</option>
<option selected value='7'>7 %</option>
<option value='19'>19 %</option>
</select>
</td>
</tr>
<tr class='container'>
<td>
<div class="box">box2</div>
</td>
<td>
<select class='vat'>
<option value='0'>0 %</option>
<option value='7'>7 %</option>
<option selected value='19'>19 %</option>
</select>
</td>
</tr>
答案 0 :(得分:1)
您的jQuery代码运行正常,问题是因为您的HTML无效。您错过了<table />
周围的tr
元素,因此渲染时布局会中断。
但请注意,您不需要.find('option:selected')
,因为您可以val()
直接获得select
元素。试试这个:
$(document).on('click', '.box', function(event) {
var result = $(this).closest('.container').find('.vat').val();
alert(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr class='container'>
<td>
<div class="box">box1</div>
</td>
<td>
<select class='vat'>
<option value='0'>0 %</option>
<option selected value='7'>7 %</option>
<option value='19'>19 %</option>
</select>
</td>
</tr>
<tr class='container'>
<td>
<div class="box">box2</div>
</td>
<td>
<select class='vat'>
<option value='0'>0 %</option>
<option value='7'>7 %</option>
<option selected value='19'>19 %</option>
</select>
</td>
</tr>
</table>