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

如何通过HTML按钮点击事件调用JavaScript类方法并显示输入用户名?

Fix: Output Inputted Username to Console on Button Click with JavaScript Class

Got it, let's break down what's going wrong here and fix it quickly.

Your current code grabs the input's value immediately when the page loads—at that point, the user hasn't had a chance to type anything, so the name variable is just an empty string. When you create the Student instance with that empty value, calling show() later will only log that empty string.

Solution 1: Fetch the Input Value When the Button is Clicked

The simplest fix is to move the input value retrieval inside the show() method, so it grabs the current value every time the button is clicked:

Updated HTML (can stay unchanged):

<body>
<input type="text" id="userName">
<button onclick="st.show()">Click</button>
</body>
<script src="script.js"></script>

Updated JavaScript:

class Student{
  show(){
    // Grab the input's current value when the method is triggered
    const currentName = document.getElementById('userName').value;
    console.log(currentName);
  }
}

// We only need to create the Student instance once
const st = new Student();

Solution 2: Separate Logic with Event Listeners (Best Practice)

If you prefer to keep your HTML and JavaScript separated (a cleaner approach for larger projects), you can ditch the inline onclick and use an event listener instead:

Updated HTML:

<body>
<input type="text" id="userName">
<button id="showNameBtn">Click</button>
</body>
<script src="script.js"></script>

Updated JavaScript:

class Student{
  showUsername(){
    const currentName = document.getElementById('userName').value;
    console.log(currentName);
  }
}

const student = new Student();
// Attach the click event listener to the button
document.getElementById('showNameBtn').addEventListener('click', () => {
  student.showUsername();
});

Why This Works

By moving the document.getElementById('userName').value call inside the method that runs on button click, we ensure we're always getting the latest value the user has typed—not the empty value from page load.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 13:22:46