我试图获取所选的选项ID。在单行中,它可以工作,但如果我添加新行,该函数仅适用于第一行。为什么呢?
$("#hobby").on('change', function () {
alert($(this).find('option:selected').attr("id"));
});

<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.js"></script>
<table id="dataTable" border=0>
<tr>
<td><input type="checkbox" name="chkstruktur[]" checked></td>
<td>
<select name="hobby" width="100px" id="hobby" >
<option id='1' value="Soccer">Soccer</option>
<option id='2' value="Running">Running</option>
<option id='3' value="Karate">Karate</option>
<option id='4' value="Bowling">Bowling</option>
</select>
</td>
</tr>
<tr>
<td><input type="checkbox" name="chkstruktur[]" checked></td>
<td>
<select name="hobby" width="100px" id="hobby" >
<option id='1' value="Soccer">Soccer</option>
<option id='2' value="Running">Running</option>
<option id='3' value="Karate">Karate</option>
<option id='4' value="Bowling">Bowling</option>
</select>
</td>
</tr>
</table>
&#13;
答案 0 :(得分:0)
id
页面中的 html
必须始终是唯一的。请将您的id
更改为class
属性,并将事件绑定到class
$('.hobby')
。休息一切都很好。
$(".hobby").on('change', function() {
alert($(this).find('option:selected').attr("id"));
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.js"></script>
<table id="dataTable" border=0>
<tr>
<td>
<input type="checkbox" name="chkstruktur[]" checked>
</td>
<td>
<select name="hobby" width="100px" class="hobby">
<option id='1' value="Soccer">Soccer</option>
<option id='2' value="Running">Running</option>
<option id='3' value="Karate">Karate</option>
<option id='4' value="Bowling">Bowling</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="chkstruktur[]" checked>
</td>
<td>
<select name="hobby" width="100px" class="hobby">
<option id='1' value="Soccer">Soccer</option>
<option id='2' value="Running">Running</option>
<option id='3' value="Karate">Karate</option>
<option id='4' value="Bowling">Bowling</option>
</select>
</td>
</tr>
</table>
&#13;