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 列表的狀態,並將新水果新增至末尾。如果水果已在「已選水果」列表中,則列表保持不變。

從這個列表中挑選你最愛的水果
您只能將新水果新增至列表,無法多次新增相同的水果。

選取水果!

<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 上編輯範例