当前位置:网站首页>for循环和单击相应函数的执行顺序问题
for循环和单击相应函数的执行顺序问题
2022-08-11 08:30:00 【LEVI_104】
问题代码如下:
//研究点击for循环和单击相应函数的执行顺序问题
window.onload = function(){
//获取所有的超链接
var allA = document.getElementsByTagName("a");
//为每一个超链接绑定一个单击响应函数
for(var i = 0; i < allA.length; i++){
allA[i].onclick = function(){
//正确代码应该是使用this,而不是allA[i],而使用allA[i]就会发生错误
//this:this指的是当前的第i个超链接本身
alert(allA[i]);
return false;
}
}
}
问题复现:当网页加载完毕,点击按钮之后,无法执行相应操作(function()函数)
分析:网页在加载的时候,执行for循环,同时赋予每一个超链接按钮一个单击响应函数。然后网页加载完毕,for循环也执行完毕了。此时,for循环的i为allA.length。当我们点击超链接按钮的时候,触发的绑定函数中的allA[i]始终是allA[allA.length],执行失败。
修改:alert(allA[i])---------------->alert(this)。分析这么做的原因:不需要allA[i]找到超链接,this会指向超链接本身
边栏推荐
- leetcode: 69. Square root of x
- 记录一些遇见的bug——Lombok和Mapstruct的冲突导致,A component required a bean of type ‘com.XXX.controller.converter.
- 【BM87 合并两个有序的数组】
- The softmax function is used in TF;
- OAuth Client默认配置加载
- 初级软件测试工程师笔试试题,你知道答案吗?
- golang string manipulation
- 分门别类输入输出,Go lang1.18入门精炼教程,由白丁入鸿儒,go lang基本数据类型和输入输出EP03
- Machine Learning Summary (2)
- Pico neo3 Unity Packaging Settings
猜你喜欢
记录一些遇见的bug——Lombok和Mapstruct的冲突导致,A component required a bean of type ‘com.XXX.controller.converter.
租房小程序
go-grpc TSL authentication solution transport: authentication handshake failed: x509 certificate relies on ... ...
Unity3D - modification of the Inspector panel of the custom class
几何EX3 功夫牛宣布停售,入门级纯电产品为何总成弃子
The easiest trick to support quick renaming of various files
OAuth Client默认配置加载
Notable NFT development trends in 2022
flex布局回顾
Redis 只会用缓存?20种妙用让同事直呼牛X(荣耀典藏版)
随机推荐
Redis 只会用缓存?20种妙用让同事直呼牛X(荣耀典藏版)
go 操作MySQL之mysql包
选择收银系统主要看哪些方面?
装饰器模式:Swift 实现
Kotlin算法入门计算素数以及优化
分门别类输入输出,Go lang1.18入门精炼教程,由白丁入鸿儒,go lang基本数据类型和输入输出EP03
Notable NFT development trends in 2022
Nuget找不到包的问题处理
Features of LoRa Chips
Getting Started with Kotlin Algorithm to Calculate the Number of Daffodils
零基础SQL教程: 主键、外键和索引 04
《剑指offer》题解——week3(持续更新)
One-hot in TF
C Primer Plus(6) 中文版 第1章 初识C语言 1.7 使用C语言的7个步骤
抽象类和接口
Alibaba Sentinel - Slot chain解析
Find the latest staff salary and the last staff salary changes
Openlayers Aggregate Graph, Weight Aggregate Graph, and Aggregate Graph Click Events
matplotlib
C Primer Plus(6) 中文版 第1章 初识C语言 1.1 C语言的起源 1.2 选择C语言的理由 1.3 C语言的应用范围