大家早上好,
我的jQuery代码目前有一些问题。我正在尝试使用cryptokickoff上的CoinMarketCap应用程序接口在我的网站上显示加密货币的统计数据。我知道如何显示它们,但是附加到我的列的操作不能正常工作。
我想要做的是:-我给出了一个数组,其中包含了我想从API中显示的密码-我想将每个密码附加到一行,该行从0 (var i)开始,每个密码加一
现在发生的情况是,所有的密码都被放入id为crypto-3的行中,我不知道这是如何发生的。
任何帮助都将不胜感激!
function fillGrid() {
var cryptos = ["bitcoin","ethereum","ripple"];
var i = 0;
jQuery(cryptos).each(function(){
jQuery.get( "https://api.coinmarketcap.com/v1/ticker/"+cryptos[i]+"/", function( data ) {
jQuery("#crypto-"+i).append(
data[0].name);
});
i++;
})
};<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script src="api.js" type="text/javascript"></script>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 col-md-6 col-lg-4" id="crypto-0">
</div>
<div class="col-sm-12 col-md-6 col-lg-4" id="crypto-1">
</div>
<div class="col-sm-12 col-md-6 col-lg-4" id="crypto-2">
</div>
</div>
<div class="row">
<div class="col-sm-12 col-md-6 col-lg-4" id="crypto-3">
</div>
<div class="col-sm-12 col-md-6 col-lg-4" id="crypto-4">
</div>
<div class="col-sm-12 col-md-6 col-lg-4" id="crypto-5">
</div>
</div>
</div>
<script type="text/javascript">
fillGrid();
</script>
</body>
</html>
发布于 2018-01-21 19:04:17
jQuery的.each通常用于遍历jQuery对象的成员(例如,如果我选择了jQuery("[id^=crypto"),我将使用.each来遍历这些成员)。使用普通的JS forEach循环进行迭代会更快。
这将在包装.get的函数的调用堆栈中维护el和i的值,因此在触发回调之前迭代器不会发生变化。
function fillGrid() {
var cryptos = ["bitcoin","ethereum","ripple"];
cryptos.forEach(function(el, i)
{
jQuery.get("https://api.coinmarketcap.com/v1/ticker/" + el + "/", function(data)
{
jQuery("#crypto-" + i).append(data[0].name);
}
);
});
};https://stackoverflow.com/questions/48366068
复制相似问题