我如何计算jQuery中的每个函数?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
目前代码在每个循环中返回<script>
ajax();
function ajax(){
$.ajax({
url:"ChinaWeather.json",
dataType:"json",
success: function(data){
$.each(data, function(index, item){
var sum = 1;
$('#countryweatherwrap').append('<div id="countryweather' + sum + '">' + data[index].season + 'Temperatuur: ' +
data[index].temperature+' °C <br />' + '<div style="height:'+ data[index].temperature*5.50 +'px;width:100%;border:1px solid #000; background-color:yellow"></div></div>'
);
});
}
})
}
</script>
。我希望它能够计算,以便返回<div id="countryweather">
,<div id="countryweather2">
等。
答案 0 :(得分:2)
一个。将var sum
移到每个循环之外(使其成为全局)
湾通过sum
++;
的值增加1
<script>
ajax();
function ajax(){
$.ajax({
url:"ChinaWeather.json",
dataType:"json",
success: function(data){
var sum = 1;
$.each(data, function(index, item){
$('#countryweatherwrap').append('<div id="countryweather' + sum + '">' + data[index].season + 'Temperatuur: ' +
data[index].temperature+' °C <br />' + '<div style="height:'+ data[index].temperature*5.50 +'px;width:100%;border:1px solid #000; background-color:yellow"></div></div>'
);
sum++;
});
}
})
}
</script>
答案 1 :(得分:1)
您可以使用索引:
$.each(data, function(index, item) {
$('#countryweatherwrap').append('<div id="countryweather' + (index+1) + '">' + data[index].season + 'Temperatuur: ' + data[index].temperature + ' °C <br />' + '<div style="height:' + data[index].temperature * 5.50 + 'px;width:100%;border:1px solid #000; background-color:yellow"></div></div>');
});
其索引从0
开始,因此请添加1
。