2017-10-07 46 views
-1

我有一個dom-repeat,我想根據函數使用src插入圖像。這次在函數中使用索引不能解決問題,現在我被卡住了。聚合物的版本是1.8.0 我試過至今不同的方式,最後一個是:錯誤「Uncaught TypeError:無法設置屬性'src'null」在dom-repeat中

<template is="dom-repeat" items="{{top.top}}" as="item"> 
     <img id="testid" src="{{imgurl}}"> 
</template> 

<script> 
    Polymer({ 
    is: 'test', 

    ready: function() { 
// Polymer.dom(this).querySelector('testid').src = this.imgurl; 
this.$.testid.src = this.imgurl; 
    } , 

properties: { 
    top: { 
     type: Array, 
     value: function() { return []; } 
    }, 

    imgurl: { 
     type: String, 
     notify: true, 
     reflectToAttribute: true, 
     computed: 'changeimg(score, oldscore)' 
     } 
    }, 

    changeimg: function(score, oldscore) { 

     if(score>oldscore){url = "images/reddown.png";} 
     else if(score<oldscore){url ="images/greenup.png";} 
     else {url = "images/blueorizontal.png";} 
     return url; 
    }, 

.... 


    }); 
</script> 

始終的結果是一樣的... 任何IDEEA?謝謝

+0

您是否嘗試過使用src $而不是src? – Ofisora

+0

您的意思是:?那麼,是的,我試圖... – vlucian

+0

你能澄清你的頂級數組的內容是什麼樣子,你想要完成什麼。你的代碼有幾個問題,我認爲不會達到你真正想要的。 – Scarygami

回答

0

問題是在行computed: 'changeimg(score, oldscore)'。您尚未定義scoreoldscore。這是計算值不是觀察者。

因此,定義這些將解決問題。

1

this.$僅適用於第一次創建時元素是元素的一部分。當使用dom-repeatdom-if時,情況並非如此,因此this.$.testid不存在,導致您看到的錯誤。

另外,您的其他嘗試使用querySelector將只返回一個img元素,但是當呈現時,您將爲每個樂譜條目都有一個img元素。

計算出的屬性imgurl也不會幫助你,因爲你的元素只有一個imgurl屬性,即使提供了分數值,它也總是相同的,無論顯示什麼分數條目。

解決問題的方法是使用computed binding計算每個顯示分數的正確img src。

<img src="[[changeimg(item.score, item.oldscore)]]"> 
+0

是!這解決了我的問題。我想我需要開始學習更多...(實際上網絡開發對我而言是一件相當新的事情)。非常感謝! – vlucian

相關問題