我有一个附加到复选框的事件处理程序。我正在使用 bootstrap 开关http://www.bootstrap-switch.org/

我试图将状态值true或false转换为变量,以便将其设置为 session 值。

当状态改变时,我可以得到true或false值(如呈现的代码所示)。但是,我想在事件中获取此值。请检查我的x变量。

client.js

Template.myTemplate.rendered = function () {
 $('input[name="questions"]').bootstrapSwitch('state', true, true);
 $('input[name="questions"]').on('switchChange.bootstrapSwitch', function(event, state) {
 console.log(state); // true | false
});

的HTML:
<template name="myTemplate">
 <div class="row">
  <input type="checkbox"  name="questions" unchecked> Hobby?
 </div>
 <div class="row">
  <input type="checkbox" name="questions" unchecked> Writer?
 </div>

我试图将在呈现的代码中的console.log(state)中打印出的值转换为事件中的变量,以便可以将 session 的值设置为true或false。
Template.myTemplate.events({
'click input': function(event) {
  var x = $(this).is(":checked").val();
  Session.set("statevalue", x);
  console.log(Session.get("statevalue")); // this is not printing out anything
 }
});

最佳答案

您应该使用模板实例:

Template.myTemplate.events({
'click input': function(event, template) {
  var x = template.$('input').is(":checked").val();
  Session.set("statevalue", x);
  console.log(Session.get("statevalue"));
 }
});

或使用“目标”:
Template.myTemplate.events({
'click input': function(event) {
  var x = $(event.target).is(":checked").val();
  Session.set("statevalue", x);
  console.log(Session.get("statevalue"));
 }
});

09-30 16:47
查看更多