You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript类方法嵌套调用问题:避免构造函数内调用方法

评分应用代码问题修复方案

原代码

class Sample {
   constructor() {
       this.btn = document.getElementById("btn");
       this.score_display = document.getElementById("display");
       this.current_container = document.getElementById("current_container");
       this.next_container = document.getElementById("next_container");
       this.scores = document.querySelectorAll(".scores")

       this.finalScore;   //final score 

       // Event listeners
        this.eventListeners();
    }

    eventListeners() {
        this.btn.addEventListener('click', () => {
            this.next_container.classList.remove('hidden');
            this.current_container.classList.add('hidden');
            
            this.getScores();
        });
    }

    getScores() {
       this.scores.forEach(score => {
            this.finalScore = 
            this.scores_display.innerHTML = this.score;
      });
   }
}

应用功能说明

  • current container(评分容器):包含可选择的评分星级
  • next container(结果容器):展示从current container选中的评分
  • 点击按钮时,为current container添加hidden类隐藏,移除next container的hidden类显示
  • getScores()方法用于计算评分并赋值给finalScore
  • 按钮点击事件中调用getScores()获取评分

问题描述

点击按钮时,next_container会在getScores()执行完成前就显示出来,导致页面展示undefined。目前可通过在构造函数中提前调用getScores()规避,但希望使用其他解决方案。

问题根源分析

  1. getScores()逻辑错误:遍历所有评分元素时,this.score是未定义属性,且forEach循环会反复覆盖finalScore,最终取值不一定是用户选中的星级。
  2. 容器切换时机错误:先显示结果容器,再去获取评分,导致页面渲染时评分值还未被正确赋值,自然显示undefined。

解决方案

调整执行顺序,先确保获取到有效评分值,再切换容器显示;同时修复getScores()的逻辑,正确获取用户选中的评分。

修改后的代码

class Sample {
   constructor() {
       this.btn = document.getElementById("btn");
       this.score_display = document.getElementById("display");
       this.current_container = document.getElementById("current_container");
       this.next_container = document.getElementById("next_container");
       this.scores = document.querySelectorAll(".scores")

       this.finalScore;  

       this.eventListeners();
    }

    eventListeners() {
        this.btn.addEventListener('click', () => {
            // 先获取并验证评分,有有效值再切换容器
            if (this.getScores()) {
                this.next_container.classList.remove('hidden');
                this.current_container.classList.add('hidden');
            } else {
                // 可选:提示用户未选择评分
                alert('请选择评分');
            }
        });
    }

    getScores() {
       // 找到用户选中的评分(假设选中的星级带有active类)
       const selectedScore = document.querySelector(".scores.active");
       if (selectedScore) {
           this.finalScore = selectedScore.dataset.score; // 从data-score属性取评分值,可根据实际DOM调整
           this.score_display.innerHTML = this.finalScore;
           return true;
       }
       // 未选中时返回false
       return false;
   }
}

修改说明

  • 调整按钮点击事件顺序:先调用getScores()获取并验证评分,只有拿到有效评分后才切换容器显示
  • 重构getScores():直接查询用户选中的星级元素(通过active类),从元素的data-score属性读取评分值(可根据实际DOM结构修改取值逻辑)
  • 添加未选中判断,可选提示用户选择评分,优化交互体验

内容的提问来源于stack exchange,提问作者jeff

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 19:30:49