动态地将属性分配给JS对象 [英] Dynamically assign properties to a JS object
问题描述
我需要动态添加属性到js对象,我通过eval()实现:
$ - >
#Methods
window.add_address =(attributes,id = new Date()。getTime()) - >
$ container = $('ul#addresses_list')
$ unit = $('< li>')
$ .each属性>
$ input = $('< input type =hidden>')
$ input.attr'name',contact [addresses_attributes] [#{id} ]
$ input.val value
$ unit.append $ input
$ container.append $ unit
#Events
#添加地址按钮
$('a#add_address')。点击,(ev) - >
attributes = new Object
$('#address_fields')。find('input')。
eval(attributes。#{$(this).attr'id'} ='#{$(this).val()}');
add_address属性
这完美的,但我觉得尴尬与< c $ c> eval(),是否还有漂亮的?我的意思是,我搜索替代品,如 Jquery .serializeArray()但它似乎只工作与查询的形式,我需要从 使用 使用以下方法创建对象也非常有效: 编辑:类似的行可以用相同的符号写入jquery方法 I needed to dynamically add properties to an js Object, which I achieved via eval():
This works perfect but I feel awkward with the Use It's also very efficient to create object using: EDIT: Along similar lines can write the jquery methods in same notation
这篇关于动态地将属性分配给JS对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!#的输入,
object ['key'] code>符号
attributes [$(this).attr('id')] = $(this)。 val();
var attributes = {};
attributes [$(this)['attr']('id')] = $(this)['val']
$ ->
#Methods
window.add_address = (attributes, id=new Date().getTime())->
$container = $('ul#addresses_list')
$unit = $('<li>')
$.each attributes, (key,value)->
$input = $('<input type="hidden">')
$input.attr 'name', "contact[addresses_attributes][#{id}][#{key}]"
$input.val value
$unit.append $input
$container.append $unit
#Events
#Add address button
$('a#add_address').on 'click', (ev)->
attributes = new Object
$('#address_fields').find('input').each ->
eval("attributes.#{$(this).attr 'id'}='#{$(this).val()}'");
add_address attributes
eval()
, is there anyway to do this "prettier"? I mean, I searched for alternatives like the Jquery .serializeArray() but it seems to work only with a queried form and I need to get the inputs from that #address_fields
div.object['key']
notationattributes[$(this).attr('id')] = $(this).val();
var attributes={};
attributes[$(this)['attr']('id')] = $(this)['val']();