您的位置:首页 > Web前端 > JQuery

jquery实现动态加载一、二级下拉菜单

2019-05-06 17:51 1521 查看
版权声明:CopyRight @CSDN 码农Robin https://blog.csdn.net/weixin_41423450/article/details/89888008

今天有个朋友问我怎么实现,点击按钮增加一级目录,选中一级目录增加二级目录

然后我写了份简单的页面实现js效果,样式就不加了。

效果图:

切换一级目录值,增加二级目录

点击按钮,增加一级目录

更换一级目录值,重新加载对应的二级目录

这个在列表查询页很常用,可以在增加一、二级目录的事件中请求后台接口,以实现动态加载搜索条件的效果

  • 注意

在追加过程中,如果通过ajax请求后台数据,实现追加元素时,需要注意在ajax的回调函数中$(this)指代的已经不再是页面dom元素了,而是ajax对象,所以需要先在ajax外部把$(this)进行赋值操作

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript" src="jquery-1.8.3.min.js"></script>
</head>
<body>
<table id="contain">
<tr>
<td>
<select name="" id="" class="sele" id="sele1">
<option class="opt" value="1">1</option>
<option class="opt" value="2">2</option>
<option class="opt" value="3">3</option>
</select>
</td>
</tr>
</table>
<button class="add">增加一二级目录</button>
</body>
</html>
<script>
$('.sele').change(function(){
$(this).nextAll().remove();
html = '';
html += '<select class="seles">';
html += '<option class="opt" value="1">1</option>';
html += '<option class="opt" value="2">2</option>';
html += '<option class="opt" value="3">3</option>';
html += '</select>';
$(this).after(html);
});
$('.add').click(function(){
html ='<tr><td>';
html += '<select class="sele">';
html += '<option class="opt" value="1">1</option>';
html += '<option class="opt" value="2">2</option>';
html += '<option class="opt" value="3">3</option>';
html += '</select>';
html += '</td></tr>';
$('#contain').append(html);
$('.sele').change(function(){
$(this).nextAll().remove();
html = '';
html += '<select class="seles">';
html += '<option class="opt" value="1">1</option>';
html += '<option class="opt" value="2">2</option>';
html += '<option class="opt" value="3">3</option>';
html += '</select>';
$(this).after(html);
});
})
</script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: