2015-10-04 92 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

相關問題