如何通过JavaScript获取点击按钮的value值?
实现点击按钮获取value值的几种方法
先给出你提供的基础HTML代码:
<div class="number"> <button type="button" value="7">7</button> <button type="button" value="8">8</button> <button type="button" value="9">9</button> <button type="button" value="4">4</button> <button type="button" value="5">5</button> </div>
方法1:直接给按钮添加onclick属性
修改HTML,给每个按钮绑定点击事件,直接传入当前按钮的value值:
<div class="number"> <button type="button" value="7" onclick="getBtnValue(this.value)">7</button> <button type="button" value="8" onclick="getBtnValue(this.value)">8</button> <button type="button" value="9" onclick="getBtnValue(this.value)">9</button> <button type="button" value="4" onclick="getBtnValue(this.value)">4</button> <button type="button" value="5" onclick="getBtnValue(this.value)">5</button> </div> <script> function getBtnValue(val) { console.log('按钮value值:', val); // 这里可以添加后续操作,比如把值展示到页面指定位置 } </script>
方法2:父元素事件委托(推荐)
利用事件冒泡特性,只给父容器绑定一次点击事件,自动处理所有子按钮的点击,新增按钮也能生效:
const numberContainer = document.querySelector('.number'); numberContainer.addEventListener('click', function(e) { // 判断点击的目标是按钮元素 if (e.target.tagName === 'BUTTON') { const btnValue = e.target.value; console.log('按钮value值:', btnValue); // 后续操作逻辑 } });
方法3:批量获取按钮并逐个绑定事件
先获取所有按钮元素,再循环给每个按钮绑定点击事件:
const buttons = document.querySelectorAll('.number button'); buttons.forEach(btn => { btn.addEventListener('click', function() { const btnValue = this.value; console.log('按钮value值:', btnValue); // 后续操作逻辑 }); });
内容的提问来源于stack exchange,提问作者fhumanity
相关产品推荐
相关产品推荐

