简体   繁体   English

Meteor onRendered-难以访问DOM

[英]Meteor onRendered - difficulty accessing DOM

I'm having trouble accessing the DOM from within a Template onRendered block in Meteor. 我在从Meteor的Template onRendered块中访问DOM时遇到问题。 Here is a simplified version of the template html: 这是模板html的简化版本:

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

And here is the client JavaScript code: 这是客户端JavaScript代码:

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

I have verified that the code is running, as the 'check' appears in the browser console, but none of the 'hi's are printed despite several images displaying. 我已验证代码是否正在运行,因为浏览器控制台中显示了“检查”,但是尽管显示了多个图像,也没有打印任何“ hi”。

In case there is a better alternate way to go about this in general, the goal here is to resize images using information from the DOM. 如果总体上有更好的替代方法,这里的目标是使用DOM中的信息来调整图像大小。

To confirm, the jquery package is added to Meteor. 为了确认,将jQuery包添加到Meteor。

Thank you in advance for any help you can provide! 预先感谢您提供的任何帮助! I've been stumped for several hours on this deceptively simple issue. 在这个看似简单的问题上,我已经迷迷了几个小时。

You shouldn't use jQuery each in your onRendered parent template. 你不应该使用jQuery each在你onRendered父模板。 Instead you can do something like: 相反,您可以执行以下操作:

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

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

js: JS:

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

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

Follow up: I'm trying to get the (natural) width and height of the image within the onRendered function, but it's returning 0, indicating that while the template has rendered the images aren't yet loaded. 后续:我正在尝试在onRendered函数中获取图像的(自然)宽度和高度,但是它返回0,表示虽然模板渲染了图像,但尚未加载。 How can I wait for the images to load? 如何等待图像加载?

Completing @juliancwirko answer, now that you have a separate template for defining your images list items, you can listen to the load event on the img tag using Meteor event maps. 完成@juliancwirko的回答后,既然您已有一个单独的模板来定义图像列表项,则可以使用流星事件映射来监听img标签上的load事件。

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

Here's what worked for me: 这对我有用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM