2010-11-22 60 views
0

我想循環使用Javascript中的名爲special_ads的Django數組。這個想法是,我可以創建Javascript 廣告對象並將它們存儲在一個Javascript數組中。 這些對象用於選擇某個廣告並顯示其他信息。如何在Javascript中使用Django for-loop?

<script type="text/javascript"> 
    ADS = new slideshow(); 
    {% for ad in special_ads %} 
    ADS.add_ad(new advert(
       "{{ ad.image }}", 
       "Drie halen twee betalen", 
       "{{ ad.company.name }}", 
       "{{ ad.description }}", 
       "{{ MEDIA_URL }}{{ ad.image }}", 
       "{% thumbnail ad.image 55x55 crop %}", 
       "brown", 
       "white" 
      )); 
    {% endfor %} 
</script> 


//================================================== 
// ad object 
//================================================== 
function advert(id,title,company,description,normal_image_src,thumb_image_src,background_color,text_color) { 
    this.id = id; 
    this.title = title; 
    this.company = company; 
    this.description = description; 
    this.normal_image_src = normal_image_src; 
    this.thumb_image_src = thumb_image_src; 
    this.background_color = background_color; 
    this.text_color = text_color; 
} 

我真的不能使用JSON名單,因爲我還需要在HTML同一陣列在頁面加載,如下圖所示。

{% for ad in special_ads %} 
    <dd> 
    <a id="std_ad_{{ i }}" class="img"> 
     <img id="{{ ad.image }}" class="enlarge" src="{% thumbnail ad.image 55x55 crop %}" alt="{{ ad.company.name }}" onclick="ADS.display(this)"/> 
    </a> 
    </dd> 
{% endfor %} 

問題是這不能正常工作。頁面加載正確,但廣告未添加到陣列。此外,Django部分似乎正確執行。頁面源代碼如下。

<script type="text/javascript"> 
    ADS = new slideshow(); 

    ADS.add_ad(new advert(
       "ads/logo_copy.jpg", 
       "Drie halen twee betalen", 
       "Directdoen.nl", 
       "DirectDoen helpt u graag met schoonmaken, tuinonderhoud en klussen. Bij DirectDoen bent u voor hulp in en om uw huis aan", 
       "http://127.0.0.1:8000/media/ads/logo_copy.jpg", 
       "", 
       "brown", 
       "white" 
      )); 

    ADS.add_ad(new advert(
       "ads/Untitled-1.jpg", 
       "Drie halen twee betalen", 
       "Jouwstraat.nl", 
       "Jouwstraat.nl is een website waar buren &amp; straatgenoten met elkaar in contact kunnen 
komen en blijven. Kijk dus snel op . 
", 
       "http://127.0.0.1:8000/media/ads/Untitled-1.jpg", 
       "", 
       "brown", 
       "white" 
      )); 

    ADS.add_ad(new advert(
       "ads/AD.JPG", 
       "Drie halen twee betalen", 
       "Code 06", 
       "DirectDoen helpt u graag met schoonmaken, tuinonderhoud en klussen. Bij DirectDoen bent u voor hulp in en om uw huis aan 
", 
       "http://127.0.0.1:8000/media/ads/AD.JPG", 
       "http://127.0.0.1:8000/media/ads/AD_JPG_55x55_crop_q95.jpg", 
       "brown", 
       "white" 
      )); 

</script> 

我已經搜索了很多,但我無法找到一個很好的教程如何做到這一點。有沒有人知道什麼是實現我的目標的最佳方式?

+0

爲什麼你不想使用JSON?如果您需要在頁面中的其他地方使用現有的版本,只需將該版本的數組創建爲JSON即可。 – 2010-11-22 19:26:56

+0

我已經嘗試過使用JSON,但它並沒有真正以我需要的方式工作。也許這確實是可能的,但我不是Django和JSON的專家;)。我現在的工作方式就是這樣。 – Marcel 2010-11-22 19:42:56

回答

0

這個問題是不正確的,因爲Django for-loop顯然不是你的問題。我想這與廣告或幻燈片類有關。你的js控制檯不會給出任何錯誤..?

相關問題