[英]How to concate function parameter value into object literal property name
I have the following JS code (also I use jQuery): 我有以下JS代码(也使用jQuery):
jQuery(function($) {
$(".to_manufacturer").click(function() {
var checked = $(this).is(':checked');
var man_id = $(this).attr("to_manufacturer_id");
update_is_in_to(man_id, "to_manufacturer", checked)
});
$(".to_model").click(function() {
var checked = $(this).is(':checked');
var man_id = $(this).attr("to_model_id");
update_is_in_to(man_id, "to_model", checked)
});
$(".to_type").click(function() {
var checked = $(this).is(':checked');
var man_id = $(this).attr("to_type_id");
update_is_in_to(man_id, "to_type", checked)
});
function update_is_in_to (man_id_val, modelname, checked_val) {
$.ajax({
url: "/admin/catalog/to/"+modelname+"s/ajax/update_is_in_to",
type: "GET",
data: {id: man_id_val, modelname_is_in_to_val: checked_val},
success: function(text)
{
//$("#total_count").html(text + " товар(ов)");
},
error: function(){
alert('Ошибка обновления объекта с id = '+man_id_val+' ! Очередная попытка...');
$.ajax(this);
},
dataType : "html"
});
}
});
How can I make it so that my param modelname_is_in_to_val
is composite, where the first part is the method param modelname
and second is the string "_is_in_to_val"
? 我怎样才能使我的参数
modelname_is_in_to_val
是复合的,其中第一部分是方法参数modelname
,第二部分是字符串"_is_in_to_val"
?
I tried modelname + "_is_in_to_val"
but I received errors. 我尝试使用
modelname + "_is_in_to_val"
但收到错误。 What is it right to do it? 这样做是正确的吗?
Also is not my code to violate according js conventions? 我的代码也不违反js约定吗?
You'll need to use bracket notation and build your object outside the function: 您将需要使用括号符号并在函数外部构建对象:
function update_is_in_to (man_id_val, modelname, checked_val) {
var data = {};
data.id = man_id_val;
data[modelname + '_is_in_to_val'] = checked_val;
$.ajax({
...
data: data,
...
});
}
You can't do it directly in the object literal syntax. 您不能直接使用对象文字语法来做到这一点。 You'll need to create the object first, then add that property using the square bracket version of the member operator.
您需要先创建对象,然后使用成员运算符的方括号版本添加该属性。 This lets you evaluate an expression, and use its result as the property name.
这使您可以评估表达式,并将其结果用作属性名称。
function update_is_in_to (man_id_val, modelname, checked_val) {
var data = {id: man_id_val};
data[modelname + "_is_in_to_val"] = checked_val;
$.ajax({
url: "/admin/catalog/to/"+modelname+"s/ajax/update_is_in_to",
type: "GET",
data: data,
success: function(text)
{
//$("#total_count").html(text + " товар(ов)");
},
error: function(){
alert('Ошибка обновления объекта с id = '+man_id_val+' ! Очередная попытка...');
$.ajax(this);
},
dataType : "html"
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.