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

Codepen投票插件迁移单页报shouldStopExecution未定义TypeError修复求助

错误根因

window.CP是Codepen平台内置的专属全局对象,用于防止死循环导致编辑器崩溃,你的代码脱离Codepen环境运行时,浏览器不存在该对象,因此触发属性读取错误,后续JS逻辑全部中断。

修复步骤
  • 移除所有Codepen专属的循环控制代码:
    1. 删除for循环内部的if (window.CP.shouldStopExecution(0)) break;
    2. 删除for循环后的window.CP.exitedLoop(0);
  • (可选适配)修正投票问题配置与页面主题匹配:
    将poll实例初始化代码修改为:
const q1 = new poll("Do You Love to Play FreeFire?", {
  0: { title: "Yes" },
  1: { title: "No" }
});
  • (可选优化)删除初始随机投票逻辑:如果不需要页面加载时自动生成20条随机测试投票,可直接删除整个for (let i = 0; i < 20; i++) {...}代码块,投票数据将从0开始统计。
修复后完整JS代码
// POLL PLUGIN
class poll {
  constructor(question, answers, options) {
    const defaultOptions = {};
    this.options = Object.assign({}, defaultOptions, options);
    this.history = [];
    this.possibleAnswers = answers;
  }

  clear() {
    this.history = [];
  }

  get results() {
    let numberOfVotes = this.history.length,
    votesResults = [];

    Object.keys(this.possibleAnswers).forEach(answerId => {
      let answerIdCounter = 0;
      let voters = [];
      this.history.forEach(vote => {
        if (answerId == vote.id) {
          answerIdCounter++;
          voters.push(vote.name);
        }
      });
      let percentOfAllVotes = answerIdCounter / numberOfVotes * 100;
      let formatedPercent = isNaN(percentOfAllVotes) ?
      0 :
      parseFloat(percentOfAllVotes).
      toFixed(3).
      slice(0, -1);
      votesResults.push({
        votes: answerIdCounter,
        voters: voters,
        percent: formatedPercent });

    });

    return votesResults;
  }

  vote(answerId, name = "Anonymouse") {
    if (this.possibleAnswers[answerId]) {
      let getCurrentDate = new Date().toLocaleString();
      this.history.push({ id: answerId, name: name, date: getCurrentDate });
      return true;
    } else throw new Error("Incorrect answer's id");
  }}

const q1 = new poll("Do You Love to Play FreeFire?", {
  0: { title: "Yes" },
  1: { title: "No" }
});


// Add some randome votes(不需要随机测试投票可删除下方整个for循环)
for (let i = 0; i < 20; i++) {
  q1.vote(Math.floor(Math.random() * (1 - 0 + 1)) + 0);
}

// Poll interface script
let pollButtons = document.querySelectorAll('.poll-panel-btn'),
pollPanel = document.querySelector('.poll-panel');
pollButtons.forEach(button => {
  button.onclick = () => {
    if (button.getAttribute('disabled') != 'disabled') {
      q1.vote(button.dataset.vote);
      pollPanel.classList.add('poll-voted');
      button.classList.add('--user-choice');
      pollButtons.forEach(b => {
        b.setAttribute('disabled', 'disabled');
        let percent = q1.results[b.dataset.vote].percent + '%';
        b.style.width = percent;
        b.dataset.result = percent;
      });
    }
  };
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 19:24:02