Meteor - 事件



在本章中,我們將學習如何使用 標籤、類id 作為事件選擇器。事件處理非常簡單。

讓我們在 HTML 模板中建立三個元素。第一個是 p,第二個是 myClass 類,最後一個是 myId id。

meteorApp.html

<head>
   <title>meteorApp</title>
</head>
 
<body>
   <div>
      {{> myTemplate}}
   </div>
</body>
 
<template name = "myTemplate">
   <p>PARAGRAPH...</p>
   <button class = "myClass">CLASS</button>
   <button id = "myId">ID</button>
</template>

在我們的 JavaScript 檔案中,我們為上面建立的三個元素設定三個事件。您會看到,我們在 click 事件之後僅新增 p、.myClass#myId。上面提到的就是這些 選擇器

meteorApp.js

if (Meteor.isClient) {

   Template.myTemplate.events({

      'click p': function() {
         console.log("The PARAGRAPH is clicked...");
      },

      'click .myClass': function() {
         console.log("The CLASS is clicked...");
      },

      'click #myId': function() {
         console.log("The ID is clicked...");
      },
   });
}

為了進行測試,我們可以先單擊 段落,然後單擊 按鈕,最後單擊 ID 按鈕。我們將獲取以下控制檯日誌。

Meteor Events Log

我們可以使用上述示例中的所有其他 JavaScript 事件,如單擊、雙擊、contextmenu、mousedown、mouseup、mouseover、mouseout、mousemove。

廣告
© . All rights reserved.