2013-05-13 49 views
1

我想要做的是轉換頁面上的所有價格與jquery,ajax和谷歌貨幣。谷歌貨幣轉換器應用到頁面上的所有價格

我發現這個,它工作正常。

$('#submit').click(function(){ 
    //Get the values 
    var amount = $('#amount').val(); 
    var from = $('#from').val(); 
    var to = $('#to').val(); 
    var params = "amount=" + amount + "&from=" + from + "&to=" + to ; 

    $.ajax({ 
     type: "POST", 
     url: "currency-converter.php", 
     data: params , 
     success: function(data){ 
      $('#converted_value').html(amount + from +" is equal to : " +data); 

     } 
    }); 
    }) ; 

如何申請這一個div類的網頁上?可以說我有一個priceEuro類;

<div class="product"> 
     <div class="priceEuro"><?php the_field('price1'); ?></div> 
</div> 

<div class="product"> 
     <div class="priceEuro"><?php the_field('price2'); ?></div> 
</div> 

<div class="product"> 
     <div class="priceEuro"><?php the_field('price3'); ?></div> 
</div> 

現在我想將所有不同的價格,結果添加到同類產品,

$('.priceEuro').each(function() { 

         var amount = $(this).val(); 
      var params = "amount=" + amount + "&from=EUR" + "&to=USD" ; 

      $.ajax({ 
       type: "POST", 
       url: "currency-converter.php", 
       data: params , 
       success: function(data){ 
       $(this).append("<div class="priceUsd">'+ data +'</div>"); 

       } 
      }); 

我知道這是不對的這些方式,以便有什麼解決辦法?謝謝。


由於@UnTechie現在我得到的結果,

$(document).ready(function() { 

    $.each($('.priceEuro'), function() { 

    var amount = $(this).text(); 
    var dataString = "amount=" + amount + "&from=EUR" + "&to=USD"; 

     $.ajax({ 
      type: "POST", 
      url: "chalo/themes/chalo/ajax_converter.php", 
      data: dataString, 
      success: function(data){ 
       console.log(data); 
       $(this).append('<div class="priceUsd">'+ data +'</div>'); 
      } 
     }); 
    }); 

}); 

,但我不能每格後,這些結果追加,這是錯的?

$(this).append('<div class="priceUsd">'+ data +'</div>'); 

好吧,我發現這個問題。 this不會自動引用ajax回調中的正確對象。

現在它的工作就是這樣,

$(document).ready(function() { 

    $.each($('.priceEuro'), function() { 
    var $this = $(this); 
    var amount = $(this).text(); 
    var dataString = "amount=" + amount + "&from=EUR" + "&to=USD"; 

     $.ajax({ 
      type: "POST", 
      url: "chalo/themes/chalo/ajax_converter.php", 
      data: dataString, 
      success: function(data){ 
       console.log(data); 
       $this.append('<div class="priceUsd">'+ data +'</div>'); 
      } 
     }); 
    }); 

}); 

回答

1

您需要使用jquery.each(http://api.jquery.com/jQuery.each/

這是你的代碼應該是什麼樣子..

$.each($('.priceEuro'), function() { 
//Your code goes here ... Use $(this) to access each element 

}); 
+0

感謝,但我不能現在每個div之後都添加這些結果,有幫助嗎? – hcx 2013-05-14 08:02:30