gpt4 book ai didi

javascript - 需要将 document.getElementsByTagName 替换为 document.getElementById

转载 作者:太空宇宙 更新时间:2023-11-04 16:13:50 24 4
gpt4 key购买 nike

我在网上找到了这段代码:

function getIPs(callback){
var ip_dups = {};
var RTCPeerConnection = window.RTCPeerConnection
|| window.mozRTCPeerConnection
|| window.webkitRTCPeerConnection;
var useWebKit = !!window.webkitRTCPeerConnection;
if(!RTCPeerConnection){
var win = iframe.contentWindow;
RTCPeerConnection = win.RTCPeerConnection
|| win.mozRTCPeerConnection
|| win.webkitRTCPeerConnection;
useWebKit = !!win.webkitRTCPeerConnection;
}
var mediaConstraints = {
optional: [{RtpDataChannels: true}]
};
var servers = {iceServers: [{urls: "stun:stun.services.mozilla.com"}]};
var pc = new RTCPeerConnection(servers, mediaConstraints);
function handleCandidate(candidate){
var ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/
var ip_addr = ip_regex.exec(candidate)[1];
if(ip_dups[ip_addr] === undefined)
callback(ip_addr);
ip_dups[ip_addr] = true;
}
pc.onicecandidate = function(ice){
//skip non-candidate events
if(ice.candidate)
handleCandidate(ice.candidate.candidate);
};
pc.createDataChannel("");
pc.createOffer(function(result){
pc.setLocalDescription(result, function(){}, function(){});
}, function(){});
setTimeout(function(){
var lines = pc.localDescription.sdp.split('\n');
lines.forEach(function(line){
if(line.indexOf('a=candidate:') === 0)
handleCandidate(line);
});
}, 1000);
}
//insert IP addresses into the page
getIPs(function(ip){
var localip = document.createElement("span");
localip.textContent = ip;
//local IPs
if (ip.match(/^(192\.168\.|169\.254\.|10\.|172\.(1[6-9]|2\d|3[01]))/))
document.getElementsByTagName("h3")[1].appendChild(localip);
});

现在我需要将 document.getElementsByTagName 更改为 document.getElementsById,删除 document.createElement("span") ,并有只有结果,因为我需要在两个地方打印它。

例如:

document.getElementById("local-ip").innerHTML = ip
<div id="local-ip"></div>

document.getElementById("local-ip2").value = ip
<input type="text" id="local-ip2" /> //here as value

我花了很多时间,但没有成功......

最佳答案

您的函数的 if () 后面没有 {} 大括号,这意味着仅执行 if () 后面的语句,因此使代码的可读性较差。

我已经将创建、文本内容 = ip、appendChild 放在一起,因此应该可以直接看到发生了什么。

只需要传递正则表达式即可。

getIPs = function() {

var ip = document.getElementById('local-ip2').value;

//local IPs

if ( ip.match(/^(192\.168\.|169\.254\.|10\.|172\.(1[6-9]|2\d|3[01]))/) ) {
//document.getElementsByTagName("h3")[1].appendChild(localip);
var localip = document.createElement("span");
localip.textContent = ip;
document.getElementById('local-ip').appendChild(localip);
}
};
<div id="local-ip"></div>
<input type="text" id="local-ip2" /> //here as value
<button onclick="getIPs()">Get IP</button>

关于javascript - 需要将 document.getElementsByTagName 替换为 document.getElementById,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41231739/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com