2014-02-21 73 views
1

我有问题。 我想perline IP地址显示国家使用http://ipinfo.ioJavascript - IP地址显示国家

这个网站码

<span>192.110.160.11</span><br> 
<span>177.67.82.22</span><br> 
<span>36.75.102.33</span><br> 

我的js

document.body.innerHTML = document.body.innerHTML.replace(new RegExp("<span>(.*?)</span>", "g"),"<span id='ip'>$1</span> - <span id='country'>wait..</span>"); 

var ip = document.getElementById("ip").innerHTML; 

$.get("http://ipinfo.io/"+ip, function (response) { 
$("#country").html(response.country); 
}, "jsonp"); 

导致我的JS,http://jsfiddle.net/p26uE

192.110.160.11 - US 
177.67.82.22 - wait.. 
36.75.102.33 - wait.. 

我想导致

192.110.160.11 - US 
177.67.82.22 - BR 
36.75.102.33 - ID 

感谢大家谁可以帮我:d

+0

ID必须是唯一的。你也只运行一次代码,你需要每个ip运行一次。 –

回答

8
$("span").each(function(i){ 
    var self = this; 
    var ip = $(this).text(); 
    $.get("http://ipinfo.io/"+ip, function (response) { 
     $(self).html(ip+"-"+response.country); 
    }, "jsonp"); 
}); 

入住这

JSFIDDLE

1

Fiddle Demo

document.body.innerHTML = document.body.innerHTML.replace(new RegExp("<span>(.*?)</span>", "g"), "<div><span class='ip'>$1</span> - <span class='country'>wait..</span></div>"); 

$('.ip').each(function() { 
    var $this = $(this); 
    $.get("http://ipinfo.io/" + $(this).text(), function (response) { 
     $this.closest('div').find('.country').html(response.country); 
    }, "jsonp"); 
}); 


Id必须是唯一的

你应该改为class。

Two HTML elements with same id attribute: How bad is it really?

1
document.body.innerHTML = document.body.innerHTML.replace(new RegExp("<span>(.*?)</span>", "g"),"<span class='country'>$1</span> - <span class='ip'>wait..</span>"); 

var ips = document.getElementsByClassName("country"); 

Array.prototype.forEach.call(ips, function(elem) { 
    var ipaddress = elem.innerHTML; 

    $.get("http://ipinfo.io/"+ipaddress, function (response) { 
    $(elem).next().html(response.country); 
    }, "jsonp"); 
}); 
0

要指定每一区间相同的ID,所以当您选择它只是返回第一跨度。尝试这样的事情,因为你已经在使用jQuery:

$('span').each(function (ele) { 
    var currEle = $(this); 
    var ip = currEle.text(); 
    $.get("http://ipinfo.io/" + ip, function (response) { 
     currEle.text(ip + " - " + response.country); 
    }, "jsonp"); 
}); 

希望这有助于

0

你可以通过它们循环。我稍微更改了设置,以便更容易循环,但您应该能够推断出需要更改的内容。

工作JSFiddle

HTML: 放入容器UL /李只是因为它们很容易做一个清单出来的

<ul id="ipList" style="list-style:none;"> 
    <li><span class="ipAddr">192.110.160.11</span><span class="ipProg">Wait...</span></li> 
    <li><span class="ipAddr">177.67.82.22</span><span class="ipProg">Wait...</span></li> 
    <li><span class="ipAddr">36.75.102.33</span><span class="ipProg">Wait...</span></li> 
</ul> 

CSS:

.ipProg{ 
    margin-left: 10px;  
} 

JS:

$(function(){ 
    $("#ipList").children('li').each(function(){   
     var ip = $(this).children('.ipAddr').first(); 
     var reg = $(this).children('.ipProg').first(); 

     $.get("http://ipinfo.io/"+ip.text(), function (response) { 
      reg.text(response.country); 
     }, "jsonp");      

    }); 


});