简体   繁体   中英

How to concate function parameter value into object literal property name

I have the following JS code (also I use 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" ?

I tried modelname + "_is_in_to_val" but I received errors. What is it right to do it?

Also is not my code to violate according js conventions?

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"
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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