Meteor onRendered - 难以访问DOM

时间:2015-05-27 15:20:56

标签: javascript jquery meteor

我在Meteor中的Template onRendered块中访问DOM时遇到问题。这是模板html的简化版本:

<template name="templateName">
  {{#each thing}}
    <img src="{{filename}}">
  {{/each}}
</template>

这是客户端JavaScript代码:

Template.templateName.onRendered(function() {
  console.log('check');
  this.$('img').each( function() {
    console.log('hi');
  });
});

我已经验证代码正在运行,因为“检查”出现在浏览器控制台中,但是尽管显示了多个图像,但没有打印出“hi”。

如果有更好的替代方法可以解决这个问题,那么这里的目标是使用DOM中的信息调整图像大小。

要确认,jquery包将添加到Meteor。

提前感谢您提供的任何帮助!在这个看似简单的问题上,我被困了几个小时。

3 个答案:

答案 0 :(得分:1)

您不应在onRendered父模板中使用jQuery each。相反,你可以做类似的事情:

<template name="templateName">
    {{#each thing}}
        {{> imgTmpl}}
    {{/each}}
</template>

<template name="imgTmpl">
    <img src="{{filename}}">
</template>

JS:

Template.templateName.onRendered(function() {
    console.log('check');
});

Template.imgTmpl.onRendered(function() {
    console.log('hi');
});

答案 1 :(得分:0)

  

跟进:我正试图获得(自然)宽度和高度   onRendered函数中的图像,但它返回0,表示   在模板渲染时,图像尚未加载。怎么样   我可以等待图片加载吗?

完成@juliancwirko答案,既然你有一个单独的模板来定义图像列表项,你可以使用Meteor事件图在img标签上收听加载事件。

Template.imgTmpl.events({
  "load img": function(event, template){
    console.log("image width :",this.$("img").prop("width"));
    console.log("image height :",this.$("img").prop("height"));
  }
});

答案 2 :(得分:0)

这对我有用:

Template.imgTmpl.events({
  "load img": function(event){
    console.log("width " + event.currentTarget.naturalWidth);
    console.log("height " + event.currentTarget.naturalHeight);
  }
});
相关问题