TypeScript匹配游戏:如何获取屏幕显示的图片?
Let’s walk through the most likely reasons your console.log is returning undefined and how to fix them:
DOM Element Timing in Angular
Angular’sngOnInitruns before the component’s view is fully rendered. If you’re usingdocument.getElementById('wrapper')here, thewrapperelement might not exist yet, leading toundefinedwhen you try to access its images.
Fix: Switch tongAfterViewInit(which runs after the view is initialized) or use Angular’sViewChildto safely reference elements. Example:import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core'; @Component({ selector: 'app-dashboard', templateUrl: './dashboard.component.html' }) export class DashboardComponent implements AfterViewInit { @ViewChild('wrapper') wrapper!: ElementRef; ngAfterViewInit(): void { const wrapperElement = this.wrapper.nativeElement; const images = wrapperElement.querySelectorAll('img'); console.log('Images:', images); // Should now log the image elements } }Don’t forget to add a template reference to your wrapper in the HTML:
<div #wrapper>...</div>Variable Scope Issues
If yourimgorimages[]variables are declared inside a nested function, loop, or conditional block, they won’t be accessible outside that scope. Double-check where you’re declaring these variables—make sure they’re in the same scope as yourconsole.logstatement.
Example of a scope mistake:ngOnInit() { if (someCondition) { const images = document.querySelectorAll('#wrapper img'); // Only accessible inside this if block } console.log(images); // Undefined! }Fix: Declare the variable outside the block if you need to access it later.
Dynamic Image Loading
If you’re setting imagesrcattributes dynamically (e.g., from an API or random array), the image elements might exist but theirsrchasn’t been set yet, or the image hasn’t finished loading. To log the image once it’s ready, use theonloadevent:const img = document.createElement('img'); img.src = 'path/to/face.jpg'; img.onload = () => { console.log('Loaded image:', img); // Logs the fully loaded image }; wrapper.appendChild(img);Incorrect Selectors
Double-check that your selector is targeting the right elements. For example, if your images have a specific class, usedocument.querySelectorAll('#wrapper .face-image')instead of a generic selector. Also, confirm thewrapperID is correctly spelled in both your HTML and TypeScript.TypeScript Type Annotations
In mixed TS/JS apps, missing type annotations can sometimes lead to unexpected behavior. Add types to your variables to catch issues early:const images: NodeListOf<HTMLImageElement> = document.querySelectorAll('#wrapper img');
These steps should help you track down why your variables are returning undefined and get your matching game’s image detection working correctly.
内容的提问来源于stack exchange,提问作者Katie Kennedy

