onclick调用接收函数作为参数的JS函数失效及语法错误排查
点击按钮获取用户私有IP的功能实现问题
已完成的前期准备
- 已编写基于
webkitRTCPeerConnection获取用户IP的getUserIP函数,该函数要求传入回调函数作为参数,用于接收获取到的IP地址
现有代码
页面结构代码
<button onclick="getUserIP(function(ip))">Click me</button> <p id="demo"></p>
交互逻辑代码
/** * 通过 webkitRTCPeerConnection 获取用户IP * @param onNewIP {Function} 用于返回获取到IP的回调函数 * @return undefined */ function getUserIP(onNewIP) { // 兼容火狐、Chrome浏览器的RTCPeerConnection实现 var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; var pc = new myPeerConnection({ iceServers: [] }), noop = function() {}, localIPs = {}, // 匹配IPv4、IPv6地址的正则 ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g, key; // 去重处理IP后触发回调 function iterateIP(ip) { if (!localIPs[ip]) onNewIP(ip); localIPs[ip] = true; } // 创建无效数据通道 pc.createDataChannel(""); // 创建Offer并设置本地SDP描述 pc.createOffer(function(sdp) { sdp.sdp.split('\n').forEach(function(line) { if (line.indexOf('candidate') < 0) return; line.match(ipRegex).forEach(iterateIP); }); pc.setLocalDescription(sdp, noop, noop); }, noop); // 监听ICE候选事件,捕获新的IP地址 pc.onicecandidate = function(ice) { if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return; ice.candidate.candidate.match(ipRegex).forEach(iterateIP); }; } // 原有的全局调用示例 getUserIP(function(ip){ document.getElementById("demo").innerHTML = '获取到你的IP:' + ip; });
遇到的问题
- 运行现有代码后页面没有任何输出,不清楚如何正确给需要接收回调的JS函数传参
自行修改尝试及报错
我修改了按钮的点击逻辑,写法如下:
<button id="a" onclick=(function(ip) { document.getElementById("demo").innerHTML = + ip; })();> 点击获取IP </button> <p id="demo"></p>
运行后浏览器控制台报出错误:
Uncaught SyntaxError: Unexpected end of input (位置:41行20列)
内容的提问来源于stack exchange,提问作者user316389
相关产品推荐
相关产品推荐

