使用jQuery分配一个html值,但在那之后jQuery返回旧值,为什么?

时间:2013-05-28 21:36:47

标签: javascript jquery

使用jQUery AJAX调用来分配表格单元格的值。该单元格是一个小计,即mysubtotalB。这很有效,因为你可以清楚地看到结果。但是在成功函数结束时,包含了对另一个jQuery函数的调用。下一个函数应该获取刚刚分配给mysubtotalB的新值,并将其添加到Total A / table cell mysubtotalA。

奇怪的部分是,即使在屏幕上将新值分配给mysubtotalB之后,通过jQuery语句返回的值也是0或原始值。玩了一会儿我注意到如果我运行第二次AJAX调用并为mysubtotalB分配了另一个值,我得到了之前的值。也就是说,jQuery赋值返回的值总是一个值。猜测DOM可能在第一次调用时没有更新,也可能与执行顺序有关,即使在调用第二个函数之前分配了总数。

有谁知道为什么会这样做以及如何处理它。

<table>
<tr>
<th>Total A</th>
<td id='mysubtotalA'>0.00</td><!-- default state when page loads -->
</tr>
<tr>
<th>Total B</th>
<td id='mysubtotalB'>0.00<td><!-- default state when page loads -->
</tr>
<tr>
<th>Grand total</th>
<td id='mygrandtotal'>0.00<td><!-- default state when page loads -->
</tr>
</table>

$.ajax({
...
success: function(returned){
$('#mysubtotalB').html(returned);//works fine returned value now on screen in mysubtotalB
}
)};

<script>
...
var theReturnedValue = $('#mysubtotalB').html();
alert('theReturnedValue');// outputs "0" the first default value
</script>

2 个答案:

答案 0 :(得分:0)

如果在成功函数调用中分配了theRururnedValue的值,该怎么办?

var theReturnedValue; //declare outside function so you can use it later
$.ajax({
.....
success: function(returned){
$('#mysubtotalb').html(returned);//works fine returned value now on screen in mysubtotalB
theReturnedValue = returned; //assign the value
alert(theReturnedValue); //alert the user
}

答案 1 :(得分:0)

使其工作的方法是设置一个对象并设置一个等于返回值的对象属性。因此在调用页面中创建了一个对象,

var mynewobject = new Object();
mynewobject.sumA = 0;
mynewobject.sumB = 0;

然后在success:function()中,将相应属性的值设置为返回值:

...    
success:  function(returned){
mynewobject.sumB = returned;
....

然后在.js文件的嵌套函数循环中,将变量设置为该值;

....
var someothernewvar = mynewobject.sumB;
....

这样能够通过AJAX调用设置值并可靠地传递多嵌套循环内的值。