javascript - 简单示例 : Setting attributes by iterating

标签 javascript jquery dom

    $(function(){

        var els = [];

        var m = $("#container");
        m.attr({"style" : "width:50%;"});

        $(".grid").each(function(e){
            els.push(this);
        });

        var n = els[3];
        n.attr({"style" : "width:50%;"}) //error
    });

你好,我是 DOM 操作的新手。我想知道为什么上面的 JQuery 为 var m 返回 [Object][Object],而为 var n 返回 [Object][HTMLDivElement]。

由于这种行为,我无法使用诸如 n.attr(args) 之类的语句。

TypeError: n.attr is not a function

最终,我想将每个 .grid 元素存储在一个数组中,并遍历它们,同时设置属性。

更准确地说,我有一个 6x3 的 div 元素网格,每次加载页面时,它们都会被赋予一个随机的 animation-duration 因为它们是动画淡入和淡出 View 的.

为什么我不能使用 n.attr()

最佳答案

那是因为 .each() 循环中的 this 是实际的 DOM 元素,而不是 jQuery 对象。如果您希望数组中的项目是 jQuery 对象,您需要自己将它们包装在一个对象中:

els.push($(this));

或者,您可以在访问 DOM 元素时将其包装起来:

var n = $(els[3]);

来自 jQuery .each() :

More importantly, the callback is fired in the context of the current DOM element, so the keyword this refers to the element.

To access a jQuery object instead of the regular DOM element, use $( this )

关于javascript - 简单示例 : Setting attributes by iterating,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48494638/

相关文章:

javascript - 如何为数组生成上一个和下一个按钮?

javascript - 如何在phonegap android中生成pdf417条形码

jQuery .css() 不适用于 background-url

javascript - 从模式对话框中的 ajax 调用中删除缓存的信息

java - 使用 DOM 解析器进行大型 XML 拆分,但我想使用 stax 解析器,以便提高性能

javascript 键码引用

javascript - 如何在 Material-ui React 表格​​中更改表格单元格宽度

javascript - 带有隐藏 ID 字段的 jQuery UI 自动完成

javascript - this.css( "color", "green"); (而不是 $(this))——它为什么有效?

javascript - DOM 元素/节点的唯一标识符是什么