country-name
如果API回报“德国”,我需要更改为“德国”。在所有其他情况下,代码都可以正常工作。无法弄清楚该怎么做。
JS:
<script type="text/javascript">
function runOnLoad() {
$.get("https://api.ipdata.co?api-key=6e6bf80b946bedd9daf3c7f799b44683b22333501994fa8af57ce0fa", function (response) {
country_name = response.country_name;
$("#country_name").text(country_name || 'Deutschland');
}, "jsonp");
}
if(document.readyState === "complete") {
runOnLoad();
} else {
window.addEventListener("onload", runOnLoad, false);
}
</script>
HTML:
<span id="country_name">Deutschland</span>
在内部使用条件运算符.text
:
$("#country_name").text(country_name === 'Germany' ? 'Deutschland' : country_name);
请记住,隐式创建全局变量不是一个好主意(甚至会在严格模式下引发错误)-最好country_name
在.get
回调中显式声明该变量:
var country_name = response.country_name;
或者,使用ES6语法:
const { country_name } = response;
或者,如果您需要为显示的名称提供多个条件,则可以嵌套条件运算符(这使内容难以理解),或使用if
/ else
:
const displayCountryName = str => $("#country_name").text(str);
// ...
const { country_name } = response;
if (country_name === 'Germany') {
displayCountryName('Deutschland');
} else if (!country_name) {
displayCountryName(/* insert your custom value here */);
} else {
displayCountryName(country_name);
}
或全部:
function runOnLoad() {
const displayCountryName = str => $("#country_name").text(str);
$.get("https://api.ipdata.co?api-key=6e6bf80b946bedd9daf3c7f799b44683b22333501994fa8af57ce0fa", function (response) {
const { country_name } = response;
if (country_name === 'Germany') {
displayCountryName('Deutschland');
} else if (!country_name) {
displayCountryName(/* insert your custom value here */);
} else {
displayCountryName(country_name);
}
}, "jsonp");
}
if(document.readyState === "complete") {
runOnLoad();
} else {
window.addEventListener("onload", runOnLoad, false);
}
如果您使用的是jQuery,则不需要if
/else
检查readyState-使用$
:
$(runOnLoad);
现场示例:
function runOnLoad() {
const displayCountryName = str => $("#country_name").text(str);
$.get("https://api.ipdata.co?api-key=6e6bf80b946bedd9daf3c7f799b44683b22333501994fa8af57ce0fa", function(response) {
const {
country_name
} = response;
if (country_name === 'Germany') {
displayCountryName('Deutschland');
} else if (!country_name) {
displayCountryName( /* insert your custom value here */ );
} else {
displayCountryName(country_name);
}
}, "jsonp");
}
$(runOnLoad);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="country_name"></div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句