2017-09-15 80 views
2

我有一个对象如下:对象值没有被正确更新

{ 
"headerSection": { 
    "text": "Some Text", 
    "color": "red", 
    "fontSize": "12px", 
    "backgroundColor": "#000", 
    "textAlign": "left" 
    } 
} 

我有一个下拉列表,用户可以选择不同的字体大小,即14px, 16px .. 20px。在这个下拉菜单中更改事件我想改变的fontSize值在我的上述对象,以便为我做的:

$('#font-size-ddl').change(function() { 
    var value = $(this).val(); 
    headerObj.fontSize = value; 
    console.log(JSON.stringify(headerObj)); 
}); 

在上面的console.log输出为:

{ 
"headerSection": { 
    "text": "Some Text", 
    "color": "red", 
    "fontSize": "12px", 
    "backgroundColor": "#000", 
    "textAlign": "left" 
}, 
"fontSize": "20px", 
} 

可有人请告诉我我做错了什么。

+0

什么是'headerObj'这里? –

+0

@HimanshuUpadhyay'headerObj'是我从服务器返回给我的对象,正如我在问题 – Code

+0

中提到的那样,我已为您的问题回答。 –

回答

1

您应该更新headerSectionfontSize属性。

在你的情况下,编译后您的headerObj对象的fontSize性质看,它没有发现它,并为您的对象的新财产

let headerObj={ 
 
"headerSection": { 
 
    "text": "Some Text", 
 
    "color": "red", 
 
    "fontSize": "12px", 
 
    "backgroundColor": "#000", 
 
    "textAlign": "left" 
 
    } 
 
} 
 

 
$('select').change(function() { 
 
    var value = $(this).val(); 
 
    headerObj.headerSection.fontSize = value; 
 
    console.log(JSON.stringify(headerObj)); 
 
}).trigger('change');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<select> 
 
    <option value="20px">20px</option> 
 
    <option value="30px">30px</option> 
 
</select>

+0

谢谢你的帮助 – Code

+0

@Code,不客气! –

+1

我的歉意,你是第一个回答它。 – Code

1

我相信,在看你的输出,该fontSize属性被不适当地附加后。

您需要执行此操作将其添加到headerSection下。

$('#font-size-ddl').change(function() { 
    var value = $(this).val(); 
    headerObj.headerSection.fontSize = value; // like this 
    console.log(JSON.stringify(headerObj)); 
}); 
+0

感谢您的帮助 – Code

1
$('#font-size-ddl').change(function() { 
    var value = $(this).val(); 
    headerObj.headerSection.fontSize = value; 
    console.log(JSON.stringify(headerObj)); 
}); 

您要添加一个值headerObj而不是headerObj.headerSection,因为你可以从执行console.log

+0

感谢您的帮助 – Code

+0

不客气,@Code – aberdeenphoenix

1

你有一个嵌套的对象看。一个嵌套的对象应该是这样的

{ 
"text": "Some Text", 
"color": "red", 
"fontSize": "12px", 
"backgroundColor": "#000", 
"textAlign": "left" 
} 

相反,你有一个外部的对象,一个叫“headerSection”的另一个对象指向特性。如果您不打算更改数据结构,那么您需要更改代码以访问内部属性。像这样的东西

$('#font-size-ddl').change(function() { 
    var value = $(this).val(); 
    headerObj["headerSection"]["fontSize"] = value; 
    console.log(JSON.stringify(headerObj)); 
}); 
+0

感谢您的帮助 – Code

1

好的,你只需要做一点改变。

$('#font-size-ddl').change(function() { 
    var value = $(this).val(); 
    headerObj.headerSection.fontSize = value; // See here. 
    console.log(JSON.stringify(headerObj)); 
}); 
+0

感谢您的帮助 – Code

+0

欢迎您的光临。乐于帮助。你也可以接受答案。 TYIA –