AMP
  • 網站

限制重複選取

簡介

這是一個範例,展示如何在 amp-list 中限制重複選取項目。此範例結合使用 amp-selectoramp-bind 來檢查項目是否已在清單中 (由 fruits 清單填充)。

如果您選取的水果已在 fruits 清單中,則 fruits 清單不會變更。

如果您選取的水果尚未在 fruits 清單中,則會將其新增至清單末尾。

<!doctype html>
<html  lang="en">
<head>
<meta charset="utf-8">
  <title>Restrict Duplicate Selection</title>
  <link rel="canonical" href="https://amp.dev.org.tw/documentation/examples/interactivity-dynamic-content/restrict_duplicate_selection/index.html">
  <meta name="viewport" content="width=device-width">
  <script async src="https://cdn.ampproject.org/v0.js"></script>

設定

匯入 amp-bind 元件以存放選取的水果

<script async custom-element="amp-bind" src="https://cdn.ampproject.org/v0/amp-bind-0.1.js"></script>

匯入 amp-list 元件以匯入要選取的水果清單

<script async custom-element="amp-list" src="https://cdn.ampproject.org/v0/amp-list-0.1.js"></script>

匯入 amp-selector 元件,讓使用者可以選擇水果

<script async custom-element="amp-selector" src="https://cdn.ampproject.org/v0/amp-selector-0.1.js"></script>

如果將 amp-selectoramp-list 搭配使用,則需要 amp-mustache 元件

<script async custom-template="amp-mustache" src="https://cdn.ampproject.org/v0/amp-mustache-0.2.js"></script>

實作

我們使用 amp-state 元素建立一個初始為空的清單,但會在使用者選取水果後更新。使用者從 amp-list 元素 (從 fruits.json 檔案匯入) 中選取水果。

每次使用者嘗試選取水果時,amp-selector 元素都會驗證水果是否已在 fruits 清單中。如果水果尚未在清單中,amp-selector 將會變更 fruits 清單的狀態,並將新水果新增至末尾。如果水果已在 fruit-selected 清單中,則清單保持不變。

從此清單中選取您最喜歡的水果
您只能將新水果新增至清單,無法多次新增相同的水果。

選擇水果!

<amp-state id="fruits">
  <script type="application/json">
    []
  </script>
</amp-state>
<p>
  Pick your favorite fruites from this list <br> You can only add new fruits to the list, you can't add the same fruit
  multiple times.
</p>
<div style="resize: horizontal; overflow: auto;">
  <p [text]="fruits">Select fruits!</p>
</div>
<amp-list src="/static/samples/json/fruits.json" height="242" items="." single-item>
  <template type="amp-mustache">
    <ul>
      <amp-selector on="select:AMP.setState({fruits: fruits.includes(event.targetOption) ? fruits : fruits.concat([event.targetOption])})">
        {{#items}}
          <li option="{{name}}" role="button" tabindex="0">
            {{name}}
          </li>
        {{/items}}
      </amp-selector>
    </ul>
  </template>
</amp-list>
需要更多說明嗎?

如果此頁面上的說明無法解答您的所有問題,請隨時與其他 AMP 使用者聯繫,討論您的確切使用案例。

前往 Stack Overflow
功能未說明?

AMP 專案非常鼓勵您的參與和貢獻!我們希望您能成為我們開放原始碼社群的長期參與者,同時也歡迎您針對您特別感興趣的問題做出一次性貢獻。

在 GitHub 上編輯範例