Javascript jQuery用值替换变量

时间:2011-08-30 16:47:56

标签: javascript jquery

我有这行Javascript jQuery代码

$.post('/blah', { comment_id: 1, description: ... });

但是,我真正需要的是能够动态地将comment_id更改为其他内容,如何将其变为可以更改的变量?

编辑

澄清,我的意思是将comment_id的值更改为photo_id,这是作业的左侧。

3 个答案:

答案 0 :(得分:7)

使用javascript变量:https://developer.mozilla.org/en/JavaScript/Guide/Values,_Variables,_and_Literals

 var commentId = 1;
 $.post('/blah', { comment_id: commentId, description: ... });

编辑:

var data = {}; // new object
data['some_name'] = 'some value';
data['another_name'] = true;
$.post('/blah', data);  // sends some_name=some value&another_name=true

编辑2:

$.post('/blah', (function () { var data = {}; // new object
  data['some_name'] = 'some value';
  data['another_name'] = true;
  return data;
}()));

答案 1 :(得分:2)

function doIt(commentId) {
  $.post('/blah', { comment_id: commentId, description: ... });
}

感谢Cameron的澄清,这是一个做OP实际要求的例子,即在对象动态中创建属性名称。

function doIt(name, value) {
  var options = {description: '', other_prop: ''};
  // This is the only way to add a dynamic property, can't use the literal
  options[name] = value;
  $.post('/blah', options);
}

答案 2 :(得分:1)

首先将对象分配给变量,以便您可以对其进行操作:

var comment_id = 17;
var options =  { description: ... };
options[comment_id] = 1;  // Now options is { 17: 1, description: ... }