0

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......我做错了什么?菜鸟

4

2 回答 2

1

尝试定义totDistance变量:

...
success: function(returnedJson){

var totDistance = 0;

jQuery.each(returnedJson, function(i, val) {
...
于 2012-06-01T19:03:30.060 回答
0

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    
}
于 2012-06-01T19:14:27.497 回答