问题描述
我需要为一个 js 对象动态添加属性,这是我通过 eval() 实现的:
I needed to dynamically add properties to an js Object, which I achieved via eval():
$ ->
#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() 很尴尬,有没有办法让这个更漂亮"?我的意思是,我搜索了像 eval() 这样的替代方法a href="http://api.jquery.com/serializeArray/" rel="nofollow">Jquery .serializeArray() 但它似乎只适用于查询表单,我需要从那个 #address_fields div.
This works perfect but I feel awkward with the 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'] 表示法
attributes[$(this).attr('id')] = $(this).val();
使用以下方法创建对象也非常有效:
It's also very efficient to create object using:
var attributes={};
类似的行可以用相同的符号编写 jquery 方法
Along similar lines can write the jquery methods in same notation
attributes[$(this)['attr']('id')] = $(this)['val']();
这篇关于将属性动态分配给 JS 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!



大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)