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

制作秒表网页时Play按钮点击后无法切换为Pause文本的问题

问题:点击Play按钮文本无法切换为Pause

我在用Tailwind CSS搭配原生JavaScript练习制作秒表网页,点击Play按钮时预期文本会切换为Pause,但实际点击后没有反应。一开始怀疑是Tailwind CSS与JavaScript冲突,实际是代码中的语法错误导致的。

原代码

HTML(搭配Tailwind CSS)

<div class="absolute top-[250px] left-[600px]">
    <div class="text-center">
        <h1 class="text-7xl font-bold text-[#f2f2f2]">00:00:00</h1>
    </div>
    <div class="flex justify-center pt-4">
        <button
          type="button"
          class="bg-[#80a5fc] hover:bg-[#6a89d2] w-24 h-16 mx-2 rounded-lg play"
        >
          Play
        </button>
        <button
          type="button"
          class="bg-[#80a5fc] hover:bg-[#6a89d2] w-24 h-16 mx-2 rounded-lg reset"
        >
          Reset
        </button>
        <button
          type="button"
          class="bg-[#80a5fc] hover:bg-[#6a89d2] w-24 h-16 mx-2 rounded-lg lap"
        >
          Lap
        </button>
     </div>
</div>

JavaScript

const playButton = document.getElementsByClassName("play")[0]
const resetButton = document.getElementsByClassName("reset")[0]
const lapButton = document.getElementsByClassName("lap")[0]

let isPlay = false

const play = () => {
    if (!isPlay) {
        playButton.innerHTML("Pause")
        isPlay = true
    }
    else {
        playButton.innerHTML("Play")
        isPlay = false
    }
}

playButton.addEventListener("click", play)

错误原因

问题出在innerHTML的用法上:innerHTML是DOM元素的属性,不是方法,不能通过括号调用的方式赋值,必须用赋值运算符=来设置内容。Tailwind CSS和JavaScript不存在冲突,此问题属于原生JavaScript的基础语法错误。

修正后的JavaScript代码

const playButton = document.getElementsByClassName("play")[0]
const resetButton = document.getElementsByClassName("reset")[0]
const lapButton = document.getElementsByClassName("lap")[0]

let isPlay = false

const play = () => {
    if (!isPlay) {
        playButton.innerHTML = "Pause"
        isPlay = true
    } else {
        playButton.innerHTML = "Play"
        isPlay = false
    }
}

playButton.addEventListener("click", play)

内容的提问来源于stack exchange,提问作者Muhammad Naseem Siddiqui

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 10:31:18