需要对这段用于捕获链接的 javascript 代码片段进行解释
需要以下代码片段来捕获我的网站的 html 链接。虽然它似乎有效,但我希望得到一个解释,以便我可以改进它。有人可以给我快速总结一下这段代码中发生的事情吗?我不太理解使用这个变量“link”的 while 语句。什么是“链接”?像在字典或映射迭代中使用的某种虚拟变量?另外,为什么使用 document.links[0] ?
if (document.links){
if (document.links[0]){
var links = document.links, link, k=0;
while(link=links[k++]) {
link.onclick = linkCapture;
}
}
}
function linkCapture() {
this.parent = this.parentNode;
eventCapture('Link Click','Page Tag',this.name,this.href);
}
The following code snippet is needed to capture html links for my site. Although, it seems to work, I wish to have an explanation so that I may improve upon it. Can someone give me a quick summary of what's happening in this code? I don't especially understand the while statement that uses this variable 'link'. What is 'link'? A dummy variable of some sort like you would use in a dictionary or map iteration? Also, why use document.links[0]?
if (document.links){
if (document.links[0]){
var links = document.links, link, k=0;
while(link=links[k++]) {
link.onclick = linkCapture;
}
}
}
function linkCapture() {
this.parent = this.parentNode;
eventCapture('Link Click','Page Tag',this.name,this.href);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
浏览器支持以下属性:
至少有一个链接:
标准初始化
对于每次循环运行,将链接设置为下一个元素,然后递增 k。当当前的
links[k]
为假时退出循环(可能是因为我们已经传递了最后一个元素)。将 onclick 属性设置为 linkCapture。
这确实不是一个很好的代码。您可以使用 jQuery 编写整个内容,如下所示:
作为奖励,您不会冒覆盖现有
onclick
属性的风险。The browser supports the property:
There is at least one link:
Standard initialization
For every run through the loop, set link to the next element, then increment k. Exit the loop when the current
links[k]
is falsy (probably because we've passed the last element).Set the onclick property to linkCapture.
This really isn't great code to begin with. You could write the whole thing using jQuery like:
As a bonus, you wouldn't risk overwriting an existing
onclick
property.