2015-10-04 93 views
2

我在我的site.html文件中有以下行。为什么我的函数没有用Meteor定义?

<input type="text" name="income" id="income" onkeydown="myFunction(this.value)"> 

我有一个单独的文件site.js看起来像这样:

if (Meteor.isClient) { 
     function myFunction(val) { 
     var income = document.getElementById("income").value; 
     } 
     var total = total + income; 
    } 

    if (Meteor.isServer) { 
     Meteor.startup(function() { 
     // code to run on server at startup 
     }); 
    } 

所以基本上我需要获得从输入字段中的值或者与模糊或类型的(onkeydown事件)和将它添加到正在页面上其他位置显示的局部变量“total”。出于某种原因,当我在控制台中输入“myFunction is not defined”时,我的功能不起作用。我需要在哪里准确地定义它(在我的.html文件中不应该使用JavaScript)。

+0

功能'myFunction'具有任何其他功能(全球范围内)之外的被声明,否则内联的事件处理程序等'的onkeydown =“myFunction的( this.value)“'看不到那个函数。一个更好的做法是使用'addEventListener'绑定事件处理程序(你说_“不应该在我的.html文件中使用JavaScript”_,但仍然使用内联事件侦听器)。 – Xufox

+0

这里是你的答案https://www.meteor.com/tutorials/blaze/creating-an-app –

+0

可能重复[JavaScript未被内联事件处理程序调用](http://stackoverflow.com/questions/14035463/javascript-not-being-being-in-in-inline-event-handler) – Xufox

回答

1

下面是一个适用于模糊事件的版本。 标记:

<body> 
    {{> hello}} 
</body> 

<template name="hello"> 
    <input type="text" name="income" id="income"> 
    <h2>{{Total}}</h2> 
</template> 

和JavaScript:

if (Meteor.isClient) { 
    // counter starts at 0 
    Session.set('total', 0); 

    Template.hello.helpers({ 
    Total: function() { 
     return Session.get('total'); 
    }, 
    }); 

    Template.hello.events({ 
    'blur #income': function (event, template) { 
     // increment the counter when button is clicked 
     Session.set('total', Session.get('total') + Number(event.target.value)); 
     event.target.value = ''; 
    }, 
    }); 
} 
+0

谢谢,我最终使用'change #income',因为输入在我的情况下不起作用(数字累加出现问题)。但是,这是我正在寻找的。我想这是一个不错的主意,因为它们非常有用,因此多研究一下事件引用。再次感谢。 – JanisOzolins

相关问题