为什么这里点击第一个div输出1而不是0呢?怎么发生了错位?
来源:2-3 鼠标事件-mousedown、mouseup
慕UI4371066
2019-03-05 19:04:46
<!DOCTYPE html> <html> <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').click(function(){ console.log($(this).index()); // $('div').eq($(this).index()).css({'text-indent':'0'}); }); }); </script> </body> </html>
1回答
你好同学 ,获取元素的index指的就是它在html代码中 , 它在兄弟元素之间所在的索引位置 . 如下 , 第一个div在兄弟元素之间排行老二 , 所以它的索引值为1 .索引为0 的是它的大哥h1标签哦 .
所以要获取当前点击的元素索引 ,可以减一 ,如下:
祝学习愉快 ,望采纳 .
相似问题