簡體   English   中英

Svelte 在事件觸發器上訪問當前元素

[英]Svelte access the current element on event trigger

我在使用this關鍵字訪問元素值時遇到問題。

這就是我所擁有的(不起作用)

{#if item}  
  <img src={'http://example.com/'+item.profile_img}
       on:error={this.src='/public/unknown.svg'}
       alt="user" />
{/if}

如果圖像不存在,我想使用'/public/unknown.svg'並將錯誤設置為null 我不明白為什么this關鍵字undefined ,正常的onerror方法也不起作用。

這是我想在 svelte 中實現的普通 HTML 版本。

<img src="http://example.com/non-existent-image.jpg"
     onerror="this.onerror=null;this.src='http://example.com/existent-image.jpg';" />

我試過各種方法都失敗了,請幫忙。

像這樣使用和內聯 function 並獲取目標然后設置 src

{#if item}  
  <img src={'http://example.com/'+item.profile_img}
       on:error={(e) => {
           e.target.src='/public/unknown.svg'
       }}
       alt="user" />
{/if}

或者,如果您更喜歡使用它,則需要使用function才能訪問正確的當前標簽

{#if item}  
  <img src={'http://example.com/'+item.profile_img}
       on:error={function() {
           this.src='/public/unknown.svg'
       }}
       alt="user" />
{/if}

閱讀更多關於箭頭功能和這個

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM