老师帮看下问题出在哪吧
来源:4-13 html5默认气泡修改演示
慕九州7567404
2019-02-17 20:55:19
<!--默认气泡样式修改试着用jq写了下,问题如下:当某一项验证正确,一项失败时,获取到的parent元素为什么会重复出现两遍?--> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.js"></script> <style type="text/css"> .box{ line-height: 30px; margin: 40px; } .box>input{ width: 60%; height: 30px; border-radius: 6px; } .box>label{ display: inline-block; width: 100px; height: 30px; line-height: 30px; text-align: center; } .box .submit{ margin-left: 100px; display: block; width: 100px; background-color: #0077aa; } .error-msg{ color: red; margin-left: 100px; font-size: 14px; } </style> </head> <body> <form action=""> <div class="box"> <label for="name">用户名:</label> <input type="text" id="name" required /> </div> <div class="box"> <label for="email">邮箱:</label> <input type="email" id="email" required /> </div> <div class="box"> <input class="submit" type="submit" value="提交" /> </div> </form> <script> var requires = $('input'); //监听 未验证成功,阻止默认事件 添加自定义错误信息提示 $('.submit').click(function () { $('.error-msg').remove(); requires.on('invalid',function () { var parent = $(this).parent(); //获取到的parent元素为什么会重复出现两遍? console.log(parent); parent.append($('<div class="error-msg">'+this.validationMessage +'</div>')); return false; }); }); </script> </body> </html>
1回答
你好,
parent获取到两个是正常的,因为有两个需要检验的input框,分别获取这两个元素的父元素。
但是两个事件需要分开,否则会进行多次校验,错误信息提示会累加,如下修改:
自己可以测试下,祝学习愉快!
相似问题