我在研究流星。在js文件中发生事件时,我需要从模板中获取值。我的值在模板中是动态的,我的代码是:
<li class="list-group-item"><span><a href="#" style="color:green" id="click_me" value="{{this}}" class="card-link"> {{stuff_Name}} </a>: {{Price}}<i class="fa fa-inr"></i></span></li>我需要js文件中事件中的value={{this}}值。我怎么才能拿到呢?
发布于 2017-03-28 19:37:46
在Meteor中,您可以在Template.events中定义事件处理程序,或者使用jQuery从dom检索数据,或者直接从数据上下文本身检索数据。
下面是一个依赖于数据上下文的示例。假设您的模板如下所示。
<template name="myTemplate">
<ul class="list-group">
{{#each stuff in lotsOfStuff}}
<li class="list-group-item">
<span>
<a href="#" style="color:green" class="card-link js-card-link">
{{stuff.stuff_Name}}
</a>: {{stuff.Price}}<i class="fa fa-inr"></i>
</span>
</li>
{{/each}}
</ul>
</template>在这里,我们迭代一个项的集合(例如lotsOfStuff),并使用每个项的属性(例如stuff_Name和Price)为每个事物创建一个列表项。
现在,我们要定义一个单击处理程序来处理对任何列表项的单击。为此,我们定义处理程序如下所示。
Template.myTemplate.events({
// in ieteor, it's best practice to use a class name starting with
// `js-` for all event handling...that is why I added the `js-card-link`
// class to the item.
'click .js-card-link'(event, instance) {
// stop the browser from handling the click
event.preventDefault();
// get whatever data we care about from the data context of this click
// e.g. you can access your entire stuff object
var stuffName = this.stuff_Name;
var price = this.Price
// you can even get items from your stuff object that were not displayed on the template
var id = this.stuffId;
// now do something with the data
},
});我们可以依赖数据上下文,因为我们在{{#each}}块中。如果您不在定义可用数据上下文的块中,则始终可以使用jQuery获取数据。
下面是一个使用jQuery的示例。再次使用此模板(注意,我向<a>添加了一个数据属性。
<template name="myTemplate">
<ul class="list-group">
{{#each stuff in lotsOfStuff}}
<li class="list-group-item">
<span>
<a href="#" style="color:green" class="card-link js-card-link" data-id="{{stuff.stuffId}}">
{{stuff.stuff_Name}}
</a>: {{stuff.Price}}<i class="fa fa-inr"></i>
</span>
</li>
{{/each}}
</ul>
</template>以下是修改后的事件处理程序。
Template.myTemplate.events({
// in ieteor, it's best practice to use a class name starting with
// `js-` for all event handling...that is why I added the `js-card-link`
// class to the item.
'click .js-card-link'(event, instance) {
// stop the browser from handling the click
event.preventDefault();
// get the value we stored in the data attribute
var id = instance.$(event.target).data('id');
// now do something with the data
},
});发布于 2017-03-28 07:36:05
锚标记没有value属性,而是可以使用data。一旦在DOM中更新了data-someKey的值,就可以使用
var getDataVal = document.getElementById('click_me').getAttribute('data-someKey')https://stackoverflow.com/questions/43063222
复制相似问题