[英]Want public variable to store IP address value in javascript
我正在尋找Localhost IP地址192.168.0.x。 我找到了可以找到Localhost IP地址的代碼。
但是,我想將值存儲到一個變量中,該變量可以讓其他函數訪問它。 就像var IPaddress =“ 192.168.0.x”;
我是新來的,我不知道該怎么做。 誰能告訴我? 非常感謝
var IPaddress;
$( document ).ready(function() {
findIP(function(ip) {
IPaddress = ip
});
new QRCode(document.getElementById("qrcode"), "http://google.com");
console.log(IPaddress);
});
function findIP(onNewIP) { // onNewIp - your listener function for new IPs
var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; //compatibility for firefox and chrome
var pc = new myPeerConnection({iceServers: []}),
noop = function() {},
localIPs = {},
ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,
key;
function ipIterate(ip) {
if (!localIPs[ip]) onNewIP(ip);
localIPs[ip] = true;
}
pc.createDataChannel(""); //create a bogus data channel
pc.createOffer(function(sdp) {
sdp.sdp.split('\n').forEach(function(line) {
if (line.indexOf('candidate') < 0) return;
line.match(ipRegex).forEach(ipIterate);
});
pc.setLocalDescription(sdp, noop, noop);
}, noop); // create offer and set local description
pc.onicecandidate = function(ice) { //listen for candidate events
if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
ice.candidate.candidate.match(ipRegex).forEach(ipIterate);
};
}
function addIP(ip) {
console.log(ip);
}
您也可以將該變量顯式設置為window
的屬性,以使其可以全局訪問。
findIP(function(ip) {
window.IPaddress = ip
})
編輯
要將值存儲在全局變量中,只需在全局范圍內定義它
var ipAddress = getIPAddress() // assumes you have a function for this
要么
window.ipAddress = getIPAddress()
在函數外部聲明的任何變量都是全局變量。
// global variable
var someGlobalThing = 'something global'
function someFunction() {
// local variable
var someLocalThing = 'something local'
console.log(someGlobalThing) // logs 'something global'
}
console.log(someLocalThing) // logs undefined
findIP具有異步調用。
以您的示例為例,console.log發生在調用回調函數之前。
您想將其他需要訪問ip參數的函數放在回調中:
findIP(function(ip) {
console.log(ip);
// other functions
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.