[英]How can I fix the way javascript runs and consolidate the way the page loads in all types of tabs
I want to be able to get an alert with my ip address when I click the button but something strange is happening: In a normal tab: The site loads and nothing happens when I click the button. 我希望能够在单击按钮时获得有关我的IP地址的警报,但发生了一些奇怪的事情:在正常选项卡中:该站点已加载,并且在单击按钮时没有任何反应。 In a private tab: The alert comes and once you press ok the button loads and on pressing nothing happens.
在一个私有选项卡中:警报出现,一旦您按OK,按钮即会加载,按此按钮则不会发生任何事情。 The javascript function ran even though I didn't use
即使我没有使用javascript函数,
How can I fix this? 我怎样才能解决这个问题? Thanks in advance
提前致谢
<!DOCTYPE html> <html> <head> <script type="application/javascript"> function getIP(json) { alert(json.ip); } </script> <script type="application/javascript" src="https://api.ipify.org?format=jsonp&callback=getIP"></script> </head> <body> <button onclick="getIP()">CLICK ME</button> </body> </html>
The function getIP
is being called when the ipify.org script finishes loading. ipify.org脚本完成加载时,将调用功能
getIP
。 If you want to only display that ip when the button is clicked, store the ip value to some variable on window
in the getIP
callback. 如果只想在单击按钮时显示该ip,请将ip值存储到
getIP
回调window
中的某个变量上。
<script type="application/javascript">
function getIP(json) {
window.ip = json.ip;
}
</script>
Now on you button you can do this to display the ip: 现在在您的按钮上,您可以执行以下操作以显示ip:
<button onclick="alert(window.ip)">CLICK ME</button>
or simply: 或者简单地:
<button onclick="alert(ip)">CLICK ME</button>
Your button click event doesn't pass in the json
parameter when it calls getIP()
. 您的按钮单击事件在调用
getIP()
时不会传递json
参数。
Instead the onclick
event needs to call another function that will make a request for https://api.ipify.org?format=jsonp&callback=getIP . 相反,
onclick
事件需要调用另一个函数,该函数将请求https://api.ipify.org?format=jsonp&callback=getIP 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.