[英]jQuery Add Key Value Pair to an Empty Object
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 inputAttr
should be an object and that I could add to that object. 我假设inputAttr
应该是一个对象,我可以添加到该对象。 I must be mistaken. 我一定是弄错了。 This was one of my many attempts to make this happen. 这是我实现这一目标的众多尝试之一。
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 inputAttr
should 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! 先感谢您!
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';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.