点赞案例 页面 页面:
<!DOCTYPE html> <html lang ="en" > <head > <meta charset ="UTF-8" > <title > 选择心仪的</title > <style > ul { list-style-type: none; } li { float: left; margin-left: 10px; } img { width: 200px; height: 180px; } input { margin-left: 30%; } </style </head > <body > <ul > <li > <img src ="images/ly.jpg" alt ="" > <br /> <input type ="button" value ="赞(1)" > </li > <li > <img src ="images/lyml.jpg" alt ="" > <br /> <input type ="button" value ="赞(1)" > </li > <li > <img src ="images/fj.jpg" alt ="" > <br /> <input type ="button" value ="赞(1)" > </li > <li > <img src ="images/bd.jpg" alt ="" > <br /> <input type ="button" value ="赞(1)" > </li > </ul > </body > <script src ="bb.js" > </script > </html >
资源 资源文件:
需要实现点击按钮,实现点赞数+1:
脚本 bb.js:
function my$ (tagName ) { return document .getElementsByTagName(tagName); } var btnObjs = my$("input" );var value = 1 ;for (var i = 0 ; i < btnObjs.length; i++) { btnObjs[i].onclick = function ( ) { this .value = "赞(" + (value++) + ")" ; }; }
可以看出,以上方式,有BUG,点击了一张照片的点赞数,会同时累加到另一张照片的点赞数当中,因为此处公用一个value,.
因此需要修复这个案例,采用闭包:
function my$ (tagName ) { return document .getElementsByTagName(tagName); } function getValue ( ) { var value = 1 ; return function ( ) { this .value = "赞(" + (++value) + ")" ; } } var btnObjs = my$("input" );for (var i = 0 ; i < btnObjs.length; i++) { btnObjs[i].onclick = getValue(); }