从 currentView 获取 jQuery 个元素

Get jQuery Element from currentView

在 api 文档中,如果提前知道选择器的属性,则可以使用选择器找到当前模板实例视图。

template.findAll(selector)
template.$(selector)

我也知道可以从 Blaze.currentView 或 template.view 获取视图,但是是否可以从 Blaze.currentView 或 template.view?我想这样做是因为我提前不知道模板实例的属性。

您可以访问绑定到模板实例或视图的第一个和最后一个 DOM 节点:

  • 模板实例上的 firstNode 和 lastNode 属性。
  • Blaze.View 实例上的 firstNode() 和 lastNode() 方法。

当您检索 DOM 元素时,您可以像往常一样使用 $ 函数从它构建一个 jQuery 对象。 HTML

<template name="test">
  <p>First paragraph</p>
  <p>Last paragraph</p>
</template>

JS

Template.test.rendered=function(){
  var $firstNode=$(this.firstNode);
  $firstNode.css("backgroundColor","red");
  //
  var $lastNode=$(this.view.lastNode());
  $lastNode.css("backgroundColor","green");
};

在此处查看 Blaze.View 完整文档:http://docs.meteor.com/#/full/blaze_view