【问题标题】:Want public variable to store IP address value in javascript希望公共变量在 javascript 中存储 IP 地址值
【发布时间】:2017-06-14 12:25:33
【问题描述】:

我正在寻找本地主机 IP 地址 192.168.0.x 。我找到了可以找到本地主机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);

}

【问题讨论】:

  • 谁能帮帮我?

标签: javascript html ip


【解决方案1】:

您还可以将该变量显式设置为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

【讨论】:

  • 我无法访问 IPaddress 变量中的值,结果是“未定义”
  • 我想将值存储到一个变量中并在其他函数中使用该变量
  • 好的,您的问题并不清楚。编辑答案。
【解决方案2】:

只需在任何函数之外定义var,它是全局的并且可供所有其他函数访问。据说有全局作用域。

var test = "this is a test";
var test2 = false;

在您的浏览器中渲染,打开您的浏览器开发者控制台并输入test,您将得到以下内容。从控制台重置它以向自己证明您有权编写它。

【讨论】:

    【解决方案3】:

    findIP 有异步调用。

    在您的示例中,console.log 发生在调用回调函数之前。

    您想将其他需要访问 ip 参数的函数放在回调中:

    findIP(function(ip) {
        console.log(ip);
        // other functions
    });    
    

    【讨论】:

      猜你喜欢
      • 2020-06-11
      • 2019-06-27
      • 2017-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 2017-04-07
      • 1970-01-01
      相关资源
      最近更新 更多