jQuery .val()问题

时间:2012-06-01 18:58:56

标签: jquery ajax

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

2 个答案:

答案 0 :(得分:1)

尝试定义totDistance变量:

...
success: function(returnedJson){

var totDistance = 0;

jQuery.each(returnedJson, function(i, val) {
...

答案 1 :(得分:0)

我认为你面临的是IE特定的问题,totDistance被评估为document.getElementById('totDistance')这就是它具有ID(totDistance)的匹配元素。为了避免这种情况,只需声明var并初始化为0。

最好将隐藏元素设置在.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    
}