应用场景
在项目中会存在大量这样的需求:
1.选择不同的radio单选框,页面上的部分内容随之显示隐藏
2.选择不同的option下拉框内容,页面上的部分内容随之显示隐藏
如果每次遇到这类需求都单独写方法,不光费时间,还会让我们的代码显得异常冗余,因此我们写个通用方法!
附上代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script> <style> .commonCss{ height: 100px; line-height: 100px; text-align: center; border: 1px solid red; } </style> </head> <body> <div class="commonCss div1 initHide">div1</div> <div class="commonCss div2 initHide">div2</div> <div class="commonCss div3 initHide">div3</div> <div> <form action=""> <div> <label>radio1</label> <input type="radio" name="radio" data-show-class=".div1" data-hide-class=".initHide"> <label>radio2</label> <input type="radio" name="radio" data-show-class=".div2" data-hide-class=".initHide"> <label>radio3</label> <input type="radio" name="radio" data-show-class=".div3" data-hide-class=".initHide"> </div> <div> <select> <option value="">请选择</option> <option value="1" data-show-class=".div1" data-hide-class=".initHide">option1</option> <option value="2" data-show-class=".div2" data-hide-class=".initHide">option2</option> <option value="3" data-show-class=".div3" data-hide-class=".initHide">option3</option> </select> </div> </form> </div> <script> var myFunction = { initRadio : function(){ $(‘input:radio‘).on(‘change‘,function(){ var $showClass = $(this).data(‘showClass‘); var $hideClass = $(this).data(‘hideClass‘); $($hideClass).hide(); $($showClass).show(); }) }, initSelect : function(){ $(‘select‘).on(‘change‘,function(){ var $target = $(this).find(‘option:selected‘); var $showClass = $target.data(‘showClass‘); var $hideClass = $target.data(‘hideClass‘); $($hideClass).hide(); $($showClass).show(); }) } }; myFunction.initRadio(); myFunction.initSelect(); </script> </body> </html>
时间: 2024-10-12 20:47:40