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 清單的末尾新增水果,以變更 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 上編輯範例