Javascript jQuery 将键值对添加到空对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25855046/
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-08-22 21:57:34  来源:igfitidea点击:

jQuery Add Key Value Pair to an Empty Object

javascriptjqueryarraysobject

提问by VIDesignz

In jQuery, I can add multiple attributes to an element like so...

在jQuery中,我可以像这样向元素添加多个属性......

var input = $('<input/>').attr({ type : 'text', value : 'New Value'});

My question is, how can I achieve this using a variable like this...

我的问题是,我怎样才能使用这样的变量来实现这一点......

var input = $('<input/>').attr(inputAttr);

I was under the assumption that inputAttrshould be an object and that I could add to that object. I must be mistaken. This was one of my many attempts to make this happen.

我假设它inputAttr应该是一个对象并且我可以添加到该对象中。我一定是弄错了。这是我为实现这一目标所做的众多尝试之一。

var inputAttr = {};
inputAttr.add({ type: 'text' });
inputAttr.add({ value : 'New Value' });

I also tried like this....

我也这样试过......

var inputAttr = {};
inputAttr.add('type: text');
inputAttr.add('value : New Value');

I thought maybe inputAttrshould be an array instead, which seems to output a correct string but not sure how to make it an object (which I think it should be).

我想也许inputAttr应该是一个数组,它似乎输出了一个正确的字符串,但不确定如何使它成为一个对象(我认为它应该是)。

var inputAttr = [];
inputAttr.push('type: text');
inputAttr.push('value : New Value');

// Then added object brackets like so
var input = $('<input/>').attr({inputAttr});

Any help would be appreciated! Thank you in advance!

任何帮助,将不胜感激!先感谢您!

回答by Gone Coding

Object properties are just accessed by name. It is not an array.

对象属性仅通过名称访问。它不是一个数组。

var inputAttr = {};
inputAttr.type = 'text';
inputAttr.value = 'New Value';

var input = $('<input/>').attr(inputAttr);

If you want to access them indirectly via keys it is like a dictionary:

如果你想通过键间接访问它们,它就像一本字典:

var inputAttr = {};
inputAttr["type"] = 'text';
inputAttr["value"] = 'New Value';

回答by Regent

Key-value for objectcan be set in this way:

object可以通过这种方式设置键值:

var inputAttr = {};
inputAttr.type = 'text';
inputAttr.value = 'New Value';

Fiddle.

小提琴