我刚刚开始使用 MeteorJS
如果我有一系列按钮,是否有办法根据我单击的按钮来更改页面的正文文本?
如果我有一个名为“Hello”的按钮,我希望将正文更改为“Hello”。
谢谢
最佳答案
使用Session
变量。
HTML
<body>
{{> main}}
</body>
<template name="main">
<p>{{text}}</p>
{{> button}}
</template>
<template name="button">
<button type="button">Hello</button>
</template>
JS
Template.main.onCreated(function(){
Session.set("text", "Default");
});
Template.main.helpers({
text: function(){
return Session.get("text");
}
});
Template.button.events({
"click button": function(event, template){
var buttonText = template.$("button").text();
Session.set("text", buttonText);
}
});
使用 ReactiveVar
避免全局变量并提供更好的组件封装。
HTML 是相同的。
JS
Template.main.onCreated(function(){
this.text = new ReactiveVar("Default");
});
Template.main.helpers({
text: function(){
return Template.instance().text.get();
}
});
Template.button.events({
"click button": function(event, template){
var buttonText = template.$("button").text();
// search for a field named text in the closest parent template (main)
template.get("text").set(buttonText);
}
});
我们需要添加 2 个包才能使此代码正常工作:
meteor add reactive-var
meteor add aldeed:template-extension
关于javascript - 更改 Meteor 应用程序文本的多个按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29408111/