老师,这里直接绑定事件到 $("div") 上和使用 each 方法有什么优劣吗
来源:2-2 编程练习
与可同学
2019-11-11 14:25:24
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>点击事件</title> <style type="text/css"> div { float: left; margin: 10px; width: 100px; height: 100px; color: #fff; font-size: 50px; text-align: center; line-height: 100px; text-indent: -9999px; background-color: #333; } </style> </head> <body> <h1>添加事件处理</h1> <div>43</div> <div>21</div> <div>56</div> <div>16</div> <div>89</div> <div>94</div> <div>46</div> <div>26</div> <div>67</div> <div>90</div> <div>25</div> <div>10</div> <div>84</div> <div>76</div> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script> <script> //此处写代码 $(document).ready(function () { $("div").each(function () { $(this).click(function () { $(this).css('text-indent', '0') }) }) }) </script> </body> </html>
1回答
同学你好,
代码实现效果没有问题,很棒哦!
优化建议:
1、jquery中的方法大部分在使用的时候前面不需要遍历元素,方法在封装的时候里面就封装了遍历,所以直接使用就好。参考:
2、和使用each方法相比,直接绑定在div上会简单,没有优劣。
如果我的回答帮助到了你,欢迎采纳!
祝学习愉快~
相似问题