js 实现 联动

mac2022-06-30  23

使用jQuery实现联动效果

应用场景:收货地址

1、准备三个下拉框
<select class="changeArea" id='province'> <option value="" > --请选择-- </option> </select> <select class="changeArea" id="city"> <option value="" > --请选择-- </option> </select> <select class="changeArea" id="area"> <option value="" > --请选择-- </option> </select>
2、由于架构是前后端分离、所以使用Ajax发送请求获取省份数据、然后渲染
<script> // 页面初始化的是时候、调用此方法 getList( 0, '#province' ) // 公共方法 - 获取数据 function getList( id, position ) { $.ajax({ method: 'get', url: "http://www.test.com/index.php/region/getList", data: { id:id }, dataType: 'json', success: function( res ) { // 判断返回的结果 if( res.code == 0 ) { var str = ' <option value=""> --请选择-- </option>' $( res.data).each( function( k,v ){ str += ' <option value="'+v.id+'">'+v.name+'</option>' }) $( position ).html( str ) } } }) } </script>
3、由于页面到现在只实现了第一个下拉框省份的数据、要实现省份发生改变的时候、城市也发生改变、为了减少代码的冗余、直接调用js公共方法
$(document).on('change', '.changeArea', function(){ var id = $(this).val() var position = $(this).next().prop('id') getList( id, '#'+position ) })
4、实现如上之后、发现数据改变的还存在问题、省份改变之后、之前选择的地区数据依旧还在、为了解决、使用如下代码
$(this).nextAll().html( '<option value=""> --请选择-- </option>' )
5、最终实现、效果如下:

6、最终的代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title> 联动 </title> </head> <body> <select class="changeArea" id='province'> <option value="" > --请选择-- </option> </select> <select class="changeArea" id="city"> <option value="" > --请选择-- </option> </select> <select class="changeArea" id="area"> <option value="" > --请选择-- </option> </select> </body> </html> <script src="__STATIC__/jquery-3.3.1.js"></script> <script> // 页面初始化的是时候、调用此方法 getList( 0, '#province' ) // 下拉框的改变事件 // 1、获取数据id // 2、获取当前下拉框之后的第一个兄弟节点的id // 3、将当前下拉框之后的所有兄弟节点的内容变为请选择 // 4、判读id是否为空、如果为空、则终止执行 // 5、调用公共方法获取对应数据 $(document).on('change', '.changeArea', function(){ var id = $(this).val() var position = $(this).next().prop('id') $(this).nextAll().html( '<option value=""> --请选择-- </option>' ) if( id == '' ) { return false; } getList( id, '#'+position ) }) // 公共方法 - 获取数据 function getList( id, position ) { $.ajax({ method: 'get', url: "http://www.test.com/index.php/region/getList", data: { id:id }, dataType: 'json', success: function( res ) { // 判断返回的结果 // 如果状态码为0、则表示返回成功、则让之后的节点显示、同时、将数据追加 // 如果状态码不是0、则表示返回失败、则让之后兄弟节点隐藏 if( res.code == 0 ) { $( position ).show() var str = ' <option value=""> --请选择-- </option>' $( res.data).each( function( k,v ){ str += ' <option value="'+v.id+'">'+v.name+'</option>' }) $( position ).html( str ) }else{ $( position ).hide() } } }) } </script>

转载于:https://www.cnblogs.com/laowenBlog/p/11290414.html

相关资源:下拉列表框的联动事件
最新回复(0)