2012-03-28 86 views
0

我试图用ajax加载器替换表单的提交按钮作为我的ajax请求的一部分。jQuery替换提交按钮

这里是我使用的代码:

beforeSend: function() { 
    $("#submit").replaceWith("<img id='loader' width ='14px' src='../img/loader.gif'>"); 
}, 
success: function(data){ 
    $("#loader").replaceWith("<input id='submit' type='submit' class='button blue' value='Get History' />"); 

这适用于第一个提交,装载机显示然后我得到的按钮回到阿贾克斯完成,但按钮不再提交表单?

编辑: 这里是形式

<form id="history" action="temp_history.php" method="post" onsubmit="getHistory();return false;" > 
<?php 
foreach($_SESSION['contacts'] as $user => $id) {?> 
<li class="contactList"><span><input type="checkbox" name="contact[]" id="contact" value="<?php echo $id; ?>" /></span><?php echo $user; ?></li> 
<?php } ?> 
</div> 
</ul> 
    <div style="bottom: 0; position: absolute; text-align: left; margin-bottom:10px; margin-left:10px; width: 210px;"> 
    <input type="text" name="days" id="days" style="border:0; color:#8a8a8a; font-weight:bold; background: url(../img/nav_secondary_bg.png);" readonly="readonly" /> 
    <div id="slider"></div> 
    <input id="submit" type="submit" class="button blue" value="Get History" /> 
    <input type="button" class="button grey" value="Clear" /> 
    </div> 
</form> 

整函数:

function getHistory() { 
    //var contact = $("#contact").val() 
    var contact = new Array(); 
     $("input[@name='contact[]']:checked").each(function() { 
     contact.push($(this).val()); 
     }); 
    var days = $("#days").val() 
    $.ajax({ 
     type: 'post', 
     url: 'temp_history.php', 
     data: {contact: contact, days: days}, 
     context: document.body, 
     beforeSend: function() { 
      $("#submit").replaceWith("<img id='loader' width ='14px' src='../img/loader.gif'>"); 
     }, 
     success: function(data){ 
      $("#loader").replaceWith("<input id='submit' type='submit' class='button blue' value='Get History' />"); 
      var json = jQuery.parseJSON(data); 
      var divs = "", tabs = "", counts = 0; 

      jQuery("#gMap").gmap3({ action: 'clear' }); 
      jQuery(".marker").remove(); 

      jQuery.each(json, function(i, item) { 
       var name = item.name; 
       var userId = item.data.user; 
       jQuery.each(item.data.data, function(i, nav) { 
        var ts = nav.timestamp; 
        var lat = nav.latitude; 
        var long = nav.longitude; 

        if (lat != null && long != null) { 
         addMarker(name, counts = counts + 1, ts, lat, long, userId); 
        } 
       }); 
      }) 
     } 
    }); 

}

+0

您可以发布你的表单代码? – 2012-03-28 11:27:42

回答

1

您将需要.replaceWith()后重新绑定您的活动,作为DOM会以一流的这是一个没有附加事件的新元素。

添加后:

$("input[type='submit'].button.blue").click(function(){ 
    getHistory(); 
}); 
+0

嗯,我会如何做到这一点。目前表单是这样提交的 -

2012-03-28 11:45:48

+0

@VinceLowe我已经更新了答案。希望这应该有所帮助。 – Curt 2012-03-28 12:16:45

+0

不改变配偶,究竟在哪里添加? – 2012-03-28 12:29:21

1

要么重新绑定在成功回调事件到submit按钮或使用事件委派.delegate