Home > Web Front-end > HTML Tutorial > image_html/css_WEB-ITnose

image_html/css_WEB-ITnose

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-24 11:34:49
Original
1159 people have browsed it


回复讨论(解决方案)

document.getElementById("aa").innerHTML = parseInt(document.getElementById("aa").innerHTML, 10) + i

用闭包

(function (i) {	img.onload = function () {		..............	}})(i);
Copy after login

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Document</title></head><body><button>button1</button> <br><button>button2</button> <br><button>button3</button> <br><button>button4</button> <br><hr><a>anchor1</a> <br><br><a>anchor2</a> <br><br><a>anchor3</a> <br><br><a>anchor4</a> <br><br><script>        var btns = document.getElementsByTagName("button");    for ( var i = 0; i < btns.length; i++ ) {        btns[i].onclick = function handler() {            //alert( this.innerHTML )            console.info( i, this.innerHTML );             /* 输出                4 "button1"                4 "button2"                4 "button3"                4 "button4"            */        }    }    alert( i ); //=> 4,JS中没有局部变量(不考虑ES6)    /*        这是因为,局部变量i在函数handler调用时,依然有效;        函数handler的调用,发生在整个for循环执行完毕后,此时i=4    */    </script>   <script>    var anchors = document.getElementsByTagName("a");    for ( var i = 0; i < btns.length; i++ ) {        ( function ( x ) {            anchors[x].onclick = function() {                console.info( x, this.innerHTML );             };        } ) ( i );    }    /*        将变量i的值传递到立即执行的函数 (function(x){})(i),        这样,每次循环, x 的值就为当次循环的i的值,而不是直接引用变量i    */</script></body></html>
Copy after login

采用闭包成功解决了问题,谢谢各位同仁大神的帮助

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
Image tag editing
From 1970-01-01 08:00:00
0
0
0
Show background image
From 1970-01-01 08:00:00
0
0
0
Modify image size
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template