javascript 将元素存储在数组中,然后在 jquery 中使用它

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17513007/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 08:35:58  来源:igfitidea点击:

Store elements inside an array then use it later in jquery

javascriptjquery

提问by Gene Sy

var els = [];
els.push($("#something"));

I need to add this to the array because the properties of #something will be changed and I need to get it's original properties (height,width position etc.)

我需要将它添加到数组中,因为 #something 的属性将被更改,我需要获取它的原始属性(高度、宽度位置等)

how do I now use the element inside els array?

我现在如何使用 els 数组中的元素?

回答by Christian Duvall

I would not store the entire object if there are only a few properties required.

如果只需要几个属性,我不会存储整个对象。

$something = $('#something');
els[$something.attr('id')] = { 
  width: $something.width(),
  height: $something.height(),
  offset: $something.offset() };

console.log(els['something']);

回答by Pointy

Well to use the saved jQuery object you'd just use normal array indexing:

要使用保存的 jQuery 对象,您只需使用普通的数组索引:

els[0].css("backgroundColor", "purple");

Now, you say that you want to save that jQuery object to preserve its state. That won't work; the jQuery object is just a wrapper that provides access to the DOM element(s) chosen by your selector. It does not copy or preserve the state of the DOM, however. If the DOM changes, then those changes will be reflected by that jQuery object and old property values won't be available.

现在,您说要保存该 jQuery 对象以保留其状态。那行不通;jQuery 对象只是一个包装器,它提供对选择器选择的 DOM 元素的访问。但是,它不会复制或保留 DOM 的状态。如果 DOM 更改,那么这些更改将反映在该 jQuery 对象上,并且旧的属性值将不可用。

If you want to preserve the state of the element, you have to do it explicitly. For example, if "something" is an <input>, you could save its value:

如果你想保留元素的状态,你必须明确地这样做。例如,如果“某物”是一个<input>,你可以保存它的值:

var savedValue = $('#something').val();

If you want to save the properties to an array:

如果要将属性保存到数组:

var els = [];
els.push({
  height: $('#something').height(),
  width: $('#something').width(),
  position: $('#something').position()
});

That'll push a whole new object (nota jQuery object; just a plain object with properties) to capture your DOM state.

这将推送一个全新的对象(不是jQuery 对象;只是一个带有属性的普通对象)来捕获您的 DOM 状态。

Now you've got a copy of the "value" property, and subsequent DOM updates won't change that.

现在您已经获得了“value”属性的副本,并且后续的 DOM 更新不会改变它。

回答by relic

You can add as many objects to the array as you like, then perform actions or get values from each of them using the array index.

您可以根据需要向数组中添加任意数量的对象,然后使用数组索引执行操作或从每个对象中获取值。

var els = [];
els.push($("#something"))
   .push($("#something-else"))
   .push($("#another"))
   .push($("#mydiv"))
;

... like so:

......像这样:

els[0].width();
els[1].css('height');
els[2].css('width','300px');
els[3].position();

els.each(function(){
    // Do stuff
}

You're essentially doing the same thing as if you saved the jquery object as a variable, and you can perform any of the same actions you might perform on that variable (or on the jquery selection directly) on the array's reference to it.

本质上,您所做的事情与将 jquery 对象保存为变量一样,并且您可以对数组对其的引用执行对该变量(或直接在 jquery 选择上)执行的任何相同操作。

回答by Xotic750

If you really want to store a copy of the "element" and its "css" so that you have everything available, then you will need to do something like this. (examples in POJS and jquery)

如果您真的想存储“元素”及其“css”的副本,以便您拥有所有可用的东西,那么您将需要做这样的事情。(POJS 和 jquery 中的例子)

CSS

CSS

#target {
    position: relative;
    top: 100px;
    left: 150px;
    height: 50px;
    width: 70px;
}

HTML

HTML

<div id="target">Text</div>

Javascript

Javascript

// IE5+ support
function snapshot(node) {
    var computedStyle = {},
    style = {},
    prop;

    if (typeof document.defaultView.getComputedStyle === "function") {
        computedStyle = document.defaultView.getComputedStyle(node, null);
    } else if (node.currentStyle) {
        computedStyle = node.currentStyle;
    } else {
        throw new Error("Unable to get a computed style.");
    }

    for (prop in computedStyle) {
        if (computedStyle.hasOwnProperty(prop)) {
            style[prop] = computedStyle[prop];
        }
    }

    return {
        node: node.cloneNode(true),
        style: style
    }
}

// Whatever jquery supports
$.fn.snapshot = function () {
    var node = this.get(0),
        computedStyle = {},
        style = {},
        prop;

    if (typeof document.defaultView.getComputedStyle === "function") {
        computedStyle = document.defaultView.getComputedStyle(node, null);
    } else if (node.currentStyle) {
        computedStyle = node.currentStyle;
    } else {
        throw new Error("Unable to get a computed style.");
    }

    for (prop in computedStyle) {
        if (computedStyle.hasOwnProperty(prop)) {
            style[prop] = this.css(prop);
        }
    }

    return {
        node: this.clone(true),
        style: style
    }
}

var snap1 = snapshot(document.getElementById("target")),
    snap2 = $("#target").snapshot();

console.log(snap1, snap2);

On jsfiddle

jsfiddle 上

If, on the other hand, what you really are after is the bounding client rectangle information. Then you could do something like this.

另一方面,如果您真正想要的是边界客户端矩形信息。那么你可以做这样的事情。

CSS

CSS

#target {
    position: relative;
    top: 100px;
    left: 150px;
    height: 50px;
    width: 70px;
}

HTML

HTML

<div id="target">Text</div>

Javascript

Javascript

// IE5+ support
var getBoundingClientRect = (function () {
    // Gecko < 1.9.1 test
    var test = document.body.getBoundingClientRect();

    // Gecko < 1.9.1
    if (!test.hasOwnProperty("height") || !test.hasOwnProperty("width")) {
        return function (node) {
            var rect = target.getBoundingClientRect();

            rect.height = rect.bottom - rect.top;
            rect.width = rect.right - rect.left;

            return rect;
        };
    }

    // Gecko >= 1.9.1
    return function (node) {
        return target.getBoundingClientRect();
    };
}());

// Whatever jquery supports
$.fn.getBoundingClientRect = function () {
    var offset = this.offset(),
        height = this.height(),
        width =this.width(),
        rect = {
            width: width,
            height: height,
            top: offset.top,
            left: offset.left,
            bottom: offset.top + height,
            right: offset.left + width
        };

    return rect;
}

var rect1 = getBoundingClientRect(document.getElementById("target")),
    rect2 = $("#target").getBoundingClientRect();

console.log(rect1, rect2);

On jsfiddle

jsfiddle 上

how do I now use the element inside els array?

我现在如何使用 els 数组中的元素?

Use standard Arraymethods to access the individual elements you stored within els.

使用标准Array方法访问您存储在els.

There are also some jquery methods available, depending on what you want to do, for example looping jQuery.each

还有一些 jquery 方法可用,这取决于你想做什么,例如循环 jQuery.each

What you "want to do" with the information is up to you, you haven't specified that in your question.

您对信息“想要做什么”取决于您,您没有在问题中指定。

回答by Ginden

You are trying to create static copy of jQuery object. It's obviously impossible (or very hard to do). You should save only important properties of an object, in way: {value: something.val()}

您正在尝试创建 jQuery 对象的静态副本。这显然是不可能的(或者很难做到)。您应该只保存对象的重要属性,方式如下: {value: something.val()}

Of course, you can create function for this.

当然,您可以为此创建函数。

function xyz (Element, List) {
    // in List you can use form 'val' for methods without arguments and ['attr', 'argument']
    // for others.
    // eg. ['val', ['attr', 'id'], ['css', 'height']]
    Element = $(Element); // to be sure it's jQuery Object
    var InfoList = {},
    i, it, MethodName, MethodArg;
    for (i = 0; i < List.length; i++) {
        it = List[i];
        if (typeof it === 'object') {
            MethodName = it[0];
            MethodArg = it[1];
            if(!InfoList[MethodName])
                InfoList[MethodName] = {};
            InfoList[MethodName][MethodArg] = Element[MethodName](MethodArg);
        }
        else if (typeof it === 'string') {
            InfoList[it] = Element[it];
        }
        else {
            console.log('O.o');
        }
    }
    return InfoList;
}

Example of output (I used th): JSON.stringify(xyz($('#hlogo'), ['html', ['attr', 'id'], 'height', ['css', 'color']]))

输出示例(我使用过): JSON.stringify(xyz($('#hlogo'), ['html', ['attr', 'id'], 'height', ['css', 'color']]))

{
  "html": "\n                <a href=\"\/\">\n                    Stack Overflow\n                <\/a>\n            ",
  "attr": {
    "id": "hlogo"
  },
  "height": 61,
  "css": {
    "color": "rgb(0, 0, 0)"
  }
}