我对JS/jQuery不太熟,目前我正试图将隐藏字段的值更改为JSON对象在循环时的特定值之和。以下是我的代码:
<form>
<input id="totDistance" type="hidden" value="" />
</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
url: "loadPolys.php",
dataType: "json",
success: function(returnedJson){
jQuery.each(returnedJson, function(i, val) {
var curType = val.type;
var curAlias = val.alias;
var curDistance = val.distance;
totDistance += parseInt(curDistance, 10);
$('#totDistance').val(totDistance);
});
},
error: function(){
alert("oh no");
}
});
});
</script>
我将输入字段始终设置为“ [object HTMLInputElement] 1734”,此外要添加的值是17和34,且正在提取数据,此外还要将totDistance设置为51......是不是哪里出错了?
Try defining the totDistance
variable:
...
success: function(returnedJson){
var totDistance = 0;
jQuery.each(returnedJson, function(i, val) {
...
I think what you are facing is an IE specific issue where it totDistance
is getting evaluated as document.getElementById('totDistance')
That is when it has an matching element with ID (totDistance). To avoid this.. simply declare the var and initialize to 0.
Also It is better to set the hidden element outside the .each
success: function(returnedJson){
var totDistance = 0; //declared a var
jQuery.each(returnedJson, function(i, val) {
var curType = val.type;
var curAlias = val.alias;
var curDistance = val.distance;
totDistance += parseInt(curDistance, 10);
});
$('#totDistance').val(totDistance); //Moved outside of .each
}