javascript - 如何仅将键及其值作为 javascript 对象的参数传递
问题描述
只是为了减少我的代码长度,我决定创建 javascript 函数来初始化 select2 插件。现在我正在编写非常冗长的代码来初始化一个元素。
$("#add_multiple_lr #trips_div .last_added .location_id").select2({
initSelection: function(element, callback) {
var elementText = $(element).attr('json-value');
callback(JSON.parse(elementText));
},
minimumInputLength: 2,
ajax: {
url: "<?php echo site_url('masters/locations/json_search'); ?>",
dataType: 'json',
type: "POST",
quietMillis: 50,
data: function (term) {
return {
term: term,
location_type: 'station',
location_county: ['india', 'bangladesh']
};
},
results: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.text,
id: item.id
}
})
};
}
}
});
对于一个或两个元素,编写此代码是可以的,但是当涉及到 10-15 个元素时,我在下面的代码中开发的代码变得非常混乱和冗长。
function initSelect2(reference, url, additional_data = {}, minimumInputLength = 2)
{
$(reference).select2({
initSelection: function(element, callback) {
var elementText = $(element).attr('json-value');
callback(JSON.parse(elementText));
},
minimumInputLength: minimumInputLength,
ajax: {
url: url,
dataType: 'json',
type: "POST",
quietMillis: 50,
data: function (term) {
return {
term: term,
additional_data
};
},
results: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.text,
id: item.id
}
})
};
}
}
});
}
并将其称为
initSelect2(
"#add_multiple_lr #lr_party, #add_multiple_lr #lr_payable_party",
"<?php echo site_url('masters/locations/json_search'); ?>",
{location_type: 'station', location_country: ['india', 'bangladesh']}
);
我只想返回附加数据(参数)的键及其属性。
解决方案
您可以为此使用扩展语法:
return {
term,
...additional_data
};
对于较旧的浏览器,您可以依赖 jQueryextend
方法(因为您似乎使用 jQuery):
return $.extend({ term: term }, additional_data);
推荐阅读
- python-3.x - Matlab 等效于 linmod 命令在 Python 中查找状态空间模型
- oracle - 游标内的集合
- java - java8 之后的 Equinox OSGi 和本机库
- javascript - 无法在“节点”上执行“removeChild”:参数 1 不是“节点”类型。在生成
- linux - 在 Linux 中更改默认文件权限
- python - 当我通过 powershell 命令窗口或 python shell 本身运行 python--version 时,找不到 Python 版本。我该如何解决?
- coq - 任何额外的公理可以使 Coq Turing 完整吗?
- django - 如何仅在 websocket 上本地显示数据
- windows - VScode终端的PATH环境变量与cmd不同
- http - 接收方是否可以减少 HTTP/2 流控制窗口?