简体   繁体   English

Javascript jQuery用值替换变量

[英]Javascript jQuery replace a variable with a value

I have this line of Javascript jQuery code 我有这行Javascript jQuery代码

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

However, what I really need is the ability to change comment_id to something else on the fly, how do I make that into a variable that I can change? 但是,我真正需要的是能够即时将comment_id更改为其他内容的功能,如何将其变成可以更改的变量?

EDIT 编辑

Clarification, I meant changing the value of comment_id to say photo_id , so the left side of the assignment. 澄清,我的意思是将comment_id的值更改为photo_id ,因此是作业的左侧。

Use a javascript variable: https://developer.mozilla.org/en/JavaScript/Guide/Values,_Variables,_and_Literals 使用JavaScript变量: https : //developer.mozilla.org/zh-CN/JavaScript/Guide/Values、_Variables、_and_Literals

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

EDIT: 编辑:

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

EDIT 2: 编辑2:

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

Thanks to the clarification from Cameron, here's an example that does what the OP actually asked for, that is to make a property name in the object dynamic. 感谢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);
}

Assign the object to a variable first so that you can manipulate it: 首先将对象分配给变量,以便您可以对其进行操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM