2017-09-15 122 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 –