2016-11-28 98 views
0

我有按鈕,有一個on.click(函數(){}。裏面的點擊功能是的setTimeout(函數(){},將顯示從外部HTML文件中的內容。如何在jQuery中顯示內容之前顯示setTimeout圖片?

<button type="button" class="btn btn-primary choose-iphone-btn">Jet Black</button> 

    $(function() { 

     $('.choose-iphone-btn').click(function() { 

      setTimeout(function() { 

       $.get('iphone-checkout.html') 
       .success(function(data) { 
        $('.iphone-pre-order-sales-content-info').html(data); 
       }); 

      }, 3000); 

     }); 

}); 

我想顯示iphone-checkout.html前顯示

<img src="images/default.gif" /> 

3秒。

任何幫助表示讚賞。

+2

在'setTimeout()'之前添加對$(「img」)。show()的調用,並在Ajax成功處理函數中調用'.hide()'? – nnnnnn

+0

你能爲我寫代碼嗎? –

+0

@redshot先試試自己,這是學習的最佳方式。做研究,你知道你需要的功能。看看jQuery API和文檔,他們有詳細的信息解釋這些功能。 –

回答

1

設置一個類來您img,說loading

<img class="loading" src="images/default.gif" /> 

顯示和隱藏的單擊事件中的相同。

$('.choose-iphone-btn').click(function() { 
    $(".loading").show(); //get reference to element with its class and show it 
    setTimeout(function() { 
     $.get('iphone-checkout.html') 
      .success(function(data) { 
       $(".loading").hide();//hide once your ajax is success 
       $('.iphone-pre-order-sales-content-info').html(data); 
     }); 
    }, 3000); 
}); 

您還可以hideloading.done事件,這樣即使在ajax故障,也不會擋住你的視線或保持顯示它。

$('.choose-iphone-btn').click(function() { 
    $(".loading").show(); //get reference to element with its class and show it 
    setTimeout(function() { 
     $.get('iphone-checkout.html') 
      .success(function(data) { 
       $('.iphone-pre-order-sales-content-info').html(data); 
      }); 
      .done(function() { 
       $(".loading").hide();//hide once your ajax request is done 
      }); 
     }, 3000); 
}); 
+1

謝謝大師! –

+0

隨時...快樂編碼.. :) –

3

創建一個類以顯示/隱藏圖像。最初將其設置爲display:none

然後使用jquery addClass & removeClass的方法來顯示和隱藏圖像

CSS

.displayNone{ 
    display:none 
} 

HTML

// added id & class to image tag 
<img id="myImage" class="displayNone" src="images/default.gif" /> 

JS

$('.choose-iphone-btn').click(function() { 
     // removing the class to display the image 
     $("#myImage").removeClass("displayNone"); 
     setTimeout(function() { 

      $.get('iphone-checkout.html') 
      .success(function(data) { 
       $('.iphone-pre-order-sales-content-info').html(data); 
       // adding class back on to hide mage on success of ajax 
       $("#myImage").addClass("displayNone"); 
      }); 

     }, 3000); 

    }); 
+0

tnx,很好的答案兄弟.. –

相關問題