我在文本区域中有 JSON。我必须通过向另一个文本框提供输入来替换 JSON 键值。
下面是我的 JSON ...我将用我将放入文本框中的值替换 name 和 zoom:max、zoom:min 的值。
{
"deployment": {
"name": "Leather Cap",
"zoom": {
"max": 400,
"min": 170
},
"scale": 6.75,
"gradient": "false",
"optional": {
"fov": 25,
"logos": "true",
"autoload": "true",
"hideInfo": "true",
"transparent": "true",
"disablePanning": "true",
"hideFullscreen": "true"
},
"rotation": {
"x": 0,
"y": 0,
"z": 0
},
"textures": {
"albedo": "albedo.jpg",
"preview": "preview.png",
"aoIntensity": 0.05,
"normalScale": 1,
"metalnessValue": 0.65,
"roughnessValue": 0.85
}
}
}
这是我的JS: 函数 updateFunc(){
const textField= document.getElementById('myText').value;
const x=JSON.parse(textField);
const fname = document.getElementById('tname');
const newName = JSON.stringify(x).replace(deployment.name, test);
x.deployment.name = JSON.parse(newName);
const zMin = document.getElementById('tZmin');
const newZmin=JSON.stringify(x).replace(deployment.zoom.min, test1);
x.deployment.zoom.min = JSON.parse(newZmin);
const zMax = document.getElementById('tZmax');
const newZmax=JSON.stringify(x).replace(deployment.zoom.max, test2);
x.deployment.zoom.max =JSON.parse(newZmax);
HTML:
<textarea name='fname'rows="1" cols='1'id='tname'></textarea><br>
zoom:<br> min:<br>
<textarea name='zoomMin'rows="1" cols='1'id='tZmin'></textarea><br>
max:<br>
<textarea name='zoomMax'rows="1" cols='1'id='tZmax'></textarea><br>
<button type='submit' onclick="updateFunc(); return false;">update JSON</button><br>
我的代码不起作用。当我单击“更新 json”按钮时。它会刷新页面。
最佳答案
这就是你如何做到这一点!我想使用您的 json 并编辑您的代码,但我无法跟踪您在上述代码中使用的某些 DOM 元素。我希望这就是您要找的。如果没有,请分享反馈。
var jsonObj = {
"deployment": {
"name": "Leather Cap",
"zoom": {
"max": 400,
"min": 170
}
}
};
document.getElementById('myText').innerHTML = JSON.stringify(jsonObj);
function updateFunc() {
let name = document.getElementById('tname').value;
let Zmin = document.getElementById('tZmin').value;
let Zmax = document.getElementById('tZmax').value;
jsonObj.deployment.name = name;
jsonObj.deployment.zoom.min = Zmin;
jsonObj.deployment.zoom.max = Zmax;
document.getElementById('myText').innerHTML = JSON.stringify(jsonObj);
}
<textarea name='fname' rows="1" cols='1' id='tname'></textarea><br> zoom:
<br> min:<br>
<textarea name='zoomMin' rows="1" cols='1' id='tZmin'></textarea><br> max:
<br>
<textarea name='zoomMax' rows="1" cols='1' id='tZmax'></textarea><br>
<button type='submit' onclick="updateFunc(); return false;">update JSON</button><br>
<div id="myText"></div>
关于javascript - 如何通过向文本框输入来替换文本区域中的 JSON 文本值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57990898/