For 语句使用 This 与 jQuery Each?

发布于 2024-12-02 03:24:25 字数 574 浏览 0 评论 0原文

我正在尝试从 $.each() 转移到 for() 语句,但在使用 $(this) 时遇到一些问题在以后?

即假设我有这个函数

$('.class').each(function() {

var myVar = $(this);
var myVarSrc = myVar.attr('src');
...

我遇到的问题是,当我尝试将其移动到 for 语句时,

var class = $('.class');
for (var i = 0; i < class.length; i++) {

var myClass = $('.class')[i];
var myClassSrc = myClass.attr('src');
...

后者不会绑定到 each 意味着 myClassSrc - 如果相同 - 将覆盖?如何将 for 语句与 this 一起使用?

I am trying to move from $.each() to a for() statement but experiencing some issues with the usage of $(this) in the later ?

i.e. assume I have this function

$('.class').each(function() {

var myVar = $(this);
var myVarSrc = myVar.attr('src');
...

The problem I experiencing is that when I attempt to move this to a for statement

var class = $('.class');
for (var i = 0; i < class.length; i++) {

var myClass = $('.class')[i];
var myClassSrc = myClass.attr('src');
...

The later doesn't bind to each meaning that myClassSrc - if it's the same - will overwrite ? How can I use a for statement with this ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

优雅的叶子 2024-12-09 03:24:25

执行 [i] 会提取本机 DOM 元素。

如果这样做,您应该直接访问 .src 属性。

var cls = $('.class');
for (var i = 0; i < cls.length; i++) {

var myClass = cls[i];
var myClassSrc = myClass.src;

...或使用 eq()[docs]< /i> 方法获取具有给定索引的元素的 jQuery 对象:

var cls = $('.class');
for (var i = 0; i < cls.length; i++) {

var myClass = cls.eq(i);
var myClassSrc = myClass.attr('src');

另请注意,我从循环内部删除了 $('.class') 。您应该使用循环之前创建的缓存版本。

我还将变量名称从 class 更改为 cls,因为 class 是 JavaScript 中未来的保留字。


根据下面的评论,您遇到了一个非常常见的问题。因为您在 for 循环内分配事件处理程序,并且 JavaScript 没有块作用域,所以这意味着您在循环中创建的每个处理程序都引用相同的 < code>myClassSrc 变量,该变量将在循环完成后设置为任何值。

为了确定变量的作用域,您需要在引用当前迭代中的值的新变量作用域中创建事件处理程序。为此,我们只需将想要保留的任何值传递到函数调用中,并在那里创建处理程序:

function set_up_handler( elem ) {

    var myClassSrc = elem.src; // <-- now this is a local variable referencing
                               //       the "src" of the element passed in.

    elem.addEventListener( 'click', function() {
        alert( myClassSrc );  // <-- this will reference the local "myClassSrc"
    }, false );

}

var cls = $('.class');
for (var i = 0; i < cls.length; i++) {

    var myClass = cls[ i ];

    set_up_handler( myClass ); // <-- pass the current element into a function

}

Doing [i] extracts the native DOM element.

If you do that, you should access the .src property directly.

var cls = $('.class');
for (var i = 0; i < cls.length; i++) {

var myClass = cls[i];
var myClassSrc = myClass.src;

...or use the eq()[docs] method to get a jQuery object with the element for the given index:

var cls = $('.class');
for (var i = 0; i < cls.length; i++) {

var myClass = cls.eq(i);
var myClassSrc = myClass.attr('src');

Also notice that I removed the $('.class') from inside the loop. You should use the cached version you made before the loop.

I also changed the variable name from class to cls since class is a future reserved word in JavaScript.


Based on the comments below, you've come a cross a very common issue. Because you're assigning event handlers inside the for loop, and because JavaScript does not have block scope, this means that every handler you create in the loop is referencing the same myClassSrc variable, which will be set at whatever value it was after the loop completed.

In order to scope a variable, you need to create the event handler in a new variable scope that references the value in the current iteration. To do this, we simply pass whatever value we want to retain into a function invocation, and create the handler there:

function set_up_handler( elem ) {

    var myClassSrc = elem.src; // <-- now this is a local variable referencing
                               //       the "src" of the element passed in.

    elem.addEventListener( 'click', function() {
        alert( myClassSrc );  // <-- this will reference the local "myClassSrc"
    }, false );

}

var cls = $('.class');
for (var i = 0; i < cls.length; i++) {

    var myClass = cls[ i ];

    set_up_handler( myClass ); // <-- pass the current element into a function

}
清醇 2024-12-09 03:24:25

我认为您不想使用 $.each 的原因是因为它很慢。它慢的原因是因为它是 jQuery。所以放弃 jQuery 并使用 DOM。

var els = document.getElementsByClassName("class");
for (var i = 0, ii = els.length; i < ii; i++) {
  var el = els[i];
  var src = el.src;
}

如果您关心旧版浏览器,您将需要一个 getElementsByClassName 的填充程序。

I assume the reason you don't want to use $.each is because it's slow. The reason it's slow is because it's jQuery. so drop jQuery and use the DOM.

var els = document.getElementsByClassName("class");
for (var i = 0, ii = els.length; i < ii; i++) {
  var el = els[i];
  var src = el.src;
}

You will need a shim for getElementsByClassName if you care about legacy browsers.

楠木可依 2024-12-09 03:24:25

这应该相当于您的 jQuery foreach 循环:

var elemList = $('.class');
for (var i = 0; i < elemList.length; i++) {

    var elem = $(elemList[i]);
    var myClassSrc = elem.attr('src');
    ...
}

如果您使用普通的 for 循环,则无需担心 this 。在 jQuery 版本中,jQuery 会将 this 绑定到正在迭代的集合中的当前元素。在非 jQuery 版本中,这相当于 elemList[i]

请注意,“class”并不是世界上最好使用的变量名称,因此我将其更改为“elemList”。事实上,它是 JavaScript 中的保留字

This should be equivalent to your jQuery foreach loop:

var elemList = $('.class');
for (var i = 0; i < elemList.length; i++) {

    var elem = $(elemList[i]);
    var myClassSrc = elem.attr('src');
    ...
}

You don't need to worry about this if you use the plain for loop. In the jQuery version, jQuery will bind this to the current element in the collection being iterated. In the non-jQuery version, that is equivalent to elemList[i].

Note that "class" is not the best variable name in the world to use, so I changed it to "elemList". It is, in fact, a reserved word in JavaScript.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文