微信小程式開發——設定預設圖片、錯誤載入圖片
阿新 • • 發佈:2019-01-05
wxml:
<image src='{{imgList[index]==""?defaultImg:imgList[index]}}' binderror="errorFunction" data-errorimg="{{index}}" />
說明: imgList: 圖片資料來源列表,需要在data中定義初始資料,或者從介面動態獲取資料; errorFunction: 圖片載入錯誤繫結的事件,錯誤圖片替換為預設圖片主要在這裡操作; data-errorimg: 錯誤圖片索引資料,需要在errorFunction中用以記錄錯誤圖片對應的位置; 如果圖片地址為空,是不會觸發binderror的,所以就直接對圖片地址做判斷,如果為空,則替換為預設圖片。
js:
data: { imgList:"", //圖片列表,動態獲取 defaultImg: "../../../assets/img/defaultImg.png", //預設圖片 }, ...... 省略圖片資料來源獲取程式碼 ...... /** * 圖片載入錯誤觸發的事件 */ errorFunction(e) { if(e.type=="error"){ var errorImgIndex = e.target.dataset.errorimg //獲取錯誤圖片迴圈的下標 var imgList= this.data.imgList //將圖片列表資料繫結到變數 imgList[errorImgIndex] = this.data.defaultImg //錯誤圖片替換為預設圖片 this.setData({ evaluteUserPic: evaluteUserPic }) } }
備註:使用這種方法,是需要將圖片資料來源放在data中的,這樣才可以在 binderror 的事件中進行資料的替換,不可以直接在wxml中呼叫介面的資料。