简体   繁体   English

jQuery单击处理程序中的范围

[英]Scope within jQuery click handler

I have a function where I get some data, and insert it into a row of a table.我有一个函数,我可以在其中获取一些数据,并将其插入到表格的一行中。

I then set up a click event on the row so that when it is clicked, it navigates to a URL specified in my data object:然后我在该行上设置了一个点击事件,以便当它被点击时,它会导航到我的数据对象中指定的 URL:

$(data).each(function(i, item) {

    var row = $("<tr></tr>");
    tbody.append(row);

    // Add some cells into the row...
    var firstNameCol = $("<td>" + item.FirstName + "</td>");
    row.append(firstNameCol);

    // Set up click handler
    row.click(function() {
       window.location.href = item.DetailsURL;
    });
 });

Now this code works fine, but it has made me realise that I'm not sure how the events work.现在这段代码工作正常,但它让我意识到我不确定事件是如何工作的。

The function contains a reference to item , which is a variable local to my for loop of items.该函数包含对item的引用,它是我的 for 项目循环的本地变量。 When the user clicks on the row, how does it know which item it is looking at?当用户单击该行时,它如何知道它正在查看哪个项目? Is it somehow cached when the click function is registered?注册点击功能时是否以某种方式缓存?

Secondly, is this method really bad?其次,这种方法真的很糟糕吗? Am I forcing it to do a load of work behind the scenes?我是在强迫它在幕后做大量工作吗?

item is a variable that's available in that scope when you bind , so that anonymous function you're passing into the .click() function just gets a copy of it (or reference if it's an object) at that time . item绑定时在该范围内可用的变量,因此您传递给.click()函数的匿名函数当时只会获取它的副本(或引用,如果它是一个对象)。

You could call this "cached", sure, but it's just a reference or a variable copy it gets at that point.当然,您可以将其称为“缓存”,但它只是当时获得的引用或变量副本。 .each() creates a closure, the callback function that you pass it ( function(i, item) {...} ), and inside there (depending on if it's an object or not, in that case you get the same reference) you get your own copy for that iteration of the loop. .each()创建一个闭包,你传递给它的回调函数( function(i, item) {...} ),并在里面(取决于它是否是一个对象,在这种情况下你会得到相同的引用) 你会为循环的那个迭代获得你自己的副本。

As for performance, this isn't a "load of work" really, it's perfectly normal.至于性能,这真的不是“工作量”,这是完全正常的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM