当options对象具有值为对象数组的属性时,如何使用jquery的extend()
方法将用户选项与默认选项合并
示例:
var settings4 = $.extend({
type: 'one-panel', // 'one-panel' | 'two-panel'
sidebarTargets: [
{
targetKey: 'sidebar-one',
initialLoadPanelKey: 'panel1',
emptyPanelMessage: '',
sidebarWrapSelectorId: 'sidebar-container',
sidebarPanelWrapTemplate: '<div class="sidebar-panel {panelInitialSlideCss}" id="{panelSelectorId}" data-panel-key="{panelKey}"></div>',
showHeader: true,
headerTemplate: '<div class="sidebar-header" id="sidebar-header">Header text</div>',
},
// if sidebarSettings.type == one-panel, this is not required
{
targetKey: 'sidebar-two',
initialLoadPanelKey: 'none',
emptyPanelMessage: '<span>No Notebooks Notes Found',
sidebarWrapSelectorId: 'sidebar-container',
sidebarPanelWrapTemplate: '<div class="sidebar-panel" id="{panelSelectorId}" data-panel-key="{panelKey}"></div>',
showHeader: true,
headerTemplate: '<div class="sidebar-header" id="sidebar-header">Header text</div>',
},
{
targetKey: 'right-content-panel',
selectorId: 'sidebar-container',
cssClassLIst: 'content-panel content',
showLoader: true, // when AJAX content is loaded, show a loader spinner
loaderTemplate: '',
initialInnerContent: '',
},
{
targetKey: 'right-content-iframe-panel',
selectorId: 'sidebar-container',
cssClassLIst: 'content-panel content',
iframeNameAttribute: 'content',
template: '<iframe id="content-frame" src="default.html" name="content" width="100%" height="100%" frameborder="0"></iframe>',
}
],
}, sidebarOptions);
sidebarTargets
以上的对象属性是有问题的。它可以包含数组中的任意数量的对象。我如何使用jQuery的扩展来合并选项并处理这样的属性?
答案 0 :(得分:0)
我担心你无法使用jQuery's extend
function真正做到这一点。
如果您发送true
in your first argument,extend
将能够扩展 对象。问题是你的对象中有Array
个,而extend
将不知道如何处理这些数组。
如果您能够将代码更改为对象,这将非常有用:
var a = {
a: ['a'],
b: {
'c': 1
}
}
var b = {
a: ['b'],
b: {
'd': 2
}
}
$.extend(a, b)
console.log('regular extend:')
console.log(a);
console.log('')
var a = {
a: ['a'],
b: {
'c': 1
}
}
var b = {
a: ['b'],
b: {
'd': 2
}
}
$.extend(true, a, b)
console.log('deep copy extend:')
console.log(a);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>