【发布时间】:2022-01-26 10:58:10
【问题描述】:
首先,我是 Javascript 和编码的新手,所以如果我的代码不够整洁或简洁,请随时提出整理方法。
我看到了一些与此主题类似的问题,但没有什么能满足我的特别需要。
我有一个运行良好的 JS 代码,它接受 JSON 输入并返回特定值:
var subtitle = document.getElementById("demo");
var title = document.getElementById("title_location");
var para1 = document.getElementById("para1");
navigator.geolocation.getCurrentPosition(showPosition);
function showPosition(position) {
var url = "https://api.opencagedata.com/geocode/v1/json?q=52.773322+-1.552661&key=592431a9da4a45b686bc75eafb005cc1" //Swadlincote (already a city so doesnt need replacing)
fetch(url)
.then(response => response.json())
.then(data => {
console.log(data)
console.log(data.results[0].components)
var stringified = JSON.stringify(data);
console.log("this is the stringified json before replacement: " + stringified)
stringifiedR = stringified.replace('"town"', '"city"');
console.log("this is the stringified json after replacement: " + stringifiedR)
var jsonObject = JSON.parse(stringifiedR);
console.log(jsonObject)
console.log("stringified city: : " + jsonObject.results[0].components.city)
subtitle.innerHTML = "Subtitle goes here: " + jsonObject.results[0].components.city
title.innerHTML = "Page Title Goes Here: " + jsonObject.results[0].components.city
para1.innerHTML = "1st paragraph of text goes here: " + jsonObject.results[0].components.city
})
}
这很好用,并从 data.results[0].components.city 返回值,这是我需要的。
我正在寻找的是一种在我对脚本执行任何操作之前检查 data.results[0].components.country 中的“国家”标签是否与“英国”匹配的方法,如果数据匹配,请继续脚本的其余部分,如果“国家”标签匹配“英国”以外的任何内容,则停止脚本。
是否有人愿意分享任何想法。
提前致谢:
【问题讨论】:
-
为什么不使用简单的
if?if(data.results[0].components.country === 'United Kingdom'){//run}
标签: javascript html parsing