2017-03-28 27 views
0

餘米的流星工作動態。我需要從我的js文件中的事件中獲取模板的值。我的價值觀是模板動態的,我的代碼是:如何從模板中的.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}}值。我怎麼才能得到它 ?提前

----- -----感謝

+0

嗨@Coder,現在還不清楚,如果你問關於模板事件是如何工作的,或者只是特別需要引用來自事件處理程序本身的數據。無論哪種方式,我希望我的答案會有幫助! – jordanwillis

回答

0

在流星,可以在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_NamePrice)的性能每一件事情創建一個列表項。

現在,我們要定義一個click處理程序來處理任何列表項的點擊。爲此,我們定義如下的處理程序。

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 
    }, 
}); 
+0

謝謝你,我的工作:),再一次你幫我...太好了! – Coder

0

有錨標籤沒有value屬性,相反,你可以使用data。 一旦值是data-someKey值是更新在DOM中,可以使用

var getDataVal = document.getElementById('click_me').getAttribute('data-someKey') 
相關問題