我如何在Meteor.js中使用元素的id来触发事件?

问题描述 投票:3回答:2

我目前使用的是Meteor 0.6.3。

下面的场景,使用'id'作为选择器,无法工作。

Template.JS:

<template name="menu">
    <div>
        <button id="showmap" class="btn-primary">Show map</button>
    </div>
</template>

JS:

Template.menu.events({
  'click #showmap' : function () {
      alert("test");
  }
});

如果我使用'class'代替'id',一切都能正常工作。

Template:

<template name="menu">
    <div>
        <button class="btn-primary showmap">Show map</button>
    </div>
</template>

JS:

Template.menu.events({
  'click .showmap' : function () {
      alert("test");
  }
});

我已经看到了好几个使用 "id "作为选择器的例子。所以我可能做錯了什麼?

javascript dom meteor dom-events
2个回答
2
投票

我试过你的代码,但没有像你说的那样工作。奇怪的是类选择器的事件也不行。不过,我加了很多包,所以如果其中一个包有干扰,我也不奇怪。

我在SO上找到了这个类似问题的回答。在流星中设置简单事件

所以你可能要在bug报告中搜索一下,如果还没有发布的话,就把它发布出来。https:/github.commeteormeteorissues)。

最好的解决方法可能是使用class作为选择器,然后对其进行测试。event.currentTarget.id 其中应该有被点击元素的id。


1
投票

我使用的是属性。id对我来说似乎也没用。比如说

<button data-do-something>
  Click Me
</button>


'click [data-do-something]': function(eventArgs, template){

}

属性的好处是你也可以给属性赋值,然后用在事件上,比如:

<button data-do-something="hello">
  Click Me
</button>


'click [data-do-something]': function(eventArgs, template){
    var data = eventArgs.target.getAttribute('data-do-something');
    if(data === 'hello') console.log('found hello!");
}
© www.soinside.com 2019 - 2024. All rights reserved.