我有一个可以添加行的页面,其中包括下拉(选择)字段。这些字段中的每一个都是动态创建的,其 ID 为“drop1、drop2、drop3”等。
我想用ajax从mysql中提取一些数据,我遇到的问题是知道哪个下拉列表已更改以提取数据。
我用它来知道当前有多少个选择字段,但不知道如何确定哪个字段已更改。如有任何帮助,我们将不胜感激。
var myCount = $("select[id^=drop]").length;
这是要添加的行。
var n=($('.detail tr').length-0)+1;
var tr = '<tr>'+
'<td>'+n+'</td>'+
'<td><select id="drop'+n+'" name="prodService[]"></select></td>'+
'<td id="desc'+n+'"></td>'+
'<td><a href="#" class="remove">Delete</a></td>'+
'</tr>';
最佳答案
围绕选择输入
的整个想法就像任何输入都接受所有事件。任何输入都需要点击
、更改
、输入
...等等,假设我们有3个选择下拉菜单。
如何检测其中是否有任何更改并获取新值
$('.select-list').on('change', function(evt) {
console.log($(this).val()); // get the select value - new value if changed
console.log($(this).attr('id')); // just for implementation purposes and debugging
});
更进一步,您可以实现类似的功能:当用户从下拉列表中选择一个项目时,向服务器发送请求以获取一些数据。您可以使用 value=""
属性来做到这一点,输入关键字/键触发(只是为了区分它们)以根据所选项目发送不同的请求。
$('.select-list').on('change', function(evt) {
console.log($(this).val()); // get the select value - new value if changed
console.log($(this).attr('id')); // just for implementation purposes and debugging
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="select-list" name="items" id="itemsList1">
<option value="1">item1</option>
<option value="2">item2</option>
<option value="3">item3</option>
<option value="4">item4</option>
</select>
<select class="select-list" name="items" id="itemsList2">
<option value="1">item1</option>
<option value="2">item2</option>
<option value="3">item3</option>
<option value="4">item4</option>
</select>
<select class="select-list" name="items" id="itemsList3">
<option value="1">item1</option>
<option value="2">item2</option>
<option value="3">item3</option>
<option value="4">item4</option>
</select>
关于javascript - 类似的选择,如何知道哪一个被改变了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53147687/