当前位置:网站首页>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会指向超链接本身
边栏推荐
- Analysis of the Status Quo of Enterprise Server Host Reinforcement
- 机器学习(三)多项式回归
- 快速幂,逆元的求解
- Interview questions about Android Service
- js将table生成excel文件并去除表格中的多余tr(js去除表格中空的tr标签)
- Write a resume like this, easy to get the interviewer
- Filesystem Hierarchy Standard
- IQUNIX A80 exploring TTC金粉 初体验
- Getting Started with Kotlin Algorithms Calculating Prime Numbers and Optimization
- Kotlin算法入门计算素数以及优化
猜你喜欢

Mysql JSON对象和JSON数组查询

Features of LoRa Chips

js将table生成excel文件并去除表格中的多余tr(js去除表格中空的tr标签)

软件测试常用工具的用途及优缺点比较(详细)

go-grpc TSL authentication solution transport: authentication handshake failed: x509 certificate relies on ... ...

The growth path of a 40W test engineer with an annual salary, which stage are you in?

囍楽cloud task source code

阿里云OSS上传文件超时 探测工具排查方法

Do you know the basic process and use case design method of interface testing?

Write a resume like this, easy to get the interviewer
随机推荐
少年成就黑客,需要这些技能
研发了 5 年的时序数据库,到底要解决什么问题?
Interaction of Pico neo3 in Unity
Kotlin Algorithm Getting Started with Rabbit Number Optimization and Expansion
oracle数据库中列转行,列会有变化
Distributed Lock-Redission - Cache Consistency Solution
第一次因没有找到iframe元素而怀疑selenium4是不是有bug?
Square, multi-power, square root calculation in Tf
excel 透视表 值显示内容 不显示计数
Getting Started with Kotlin Algorithm to Calculate the Number of Daffodils
Find the latest staff salary and the last staff salary changes
关于架构的认知
The softmax function is used in TF;
Interview questions about Android Service
[UEFI]EFI_DEVICE_PATH_PROTOCOL 结构体初始化的一个例子
小程序组件不能修改ui组件样式
3.1-Classification-probabilistic generative model
Nuget找不到包的问题处理
RestTemplate工具类
jenkins简单使用