2017-10-13 59 views
1

我想更改json數組的具體值。查看詳細我有這個DOM:更改數據屬性json值

<input class="fileupload" type="file" data-form-data='{"table_reference": "data_monitoring", "table_token" : "X43sd"}'>   

我知道如何使用jQuery使用此代碼更新數據屬性:$(本).attr( '鍵', '值')

但我如何改變數據屬性的特定鍵,例如上面DOM 需要改變table_token

感謝任何建議

回答

3

您可以使用.data()財產參照特定的屬性設置爲一個值

$(".fileupload").data().formData.table_token = 123; 
 

 
console.log($(".fileupload").data().formData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input class="fileupload" type="file" data-form-data='{"table_reference": "data_monitoring", "table_token" : "X43sd"}'>

如果需求是設置data-*將在HTML中反映出來,你可以使用HTMLElement.dataset

var new_token = "abc"; 

let data = JSON.parse($(".fileupload")[0].dataset.formData); 

data.table_token = new_token; 

$(".fileupload")[0].dataset.formData = JSON.stringify(data); 
+0

我想你意思是'.data().formData.table_token' –

+0

不工作???? https://jsfiddle.net/3gd0qv2x/ – navotera

+0

@navotera不確定你的意思?該屬性設置在'.data()'對象 – guest271314