如何使用DOM获取元素:点击复选框时获取对应hello元素引用
点击复选框获取对应元素引用的实现方法
下面给你几种实用的实现方式,根据你的DOM结构选合适的就行:
利用DOM层级关系直接获取
如果复选框和目标“hello”元素是相邻兄弟(比如复选框紧跟在元素前后),或者同属一个父容器,直接在pass函数里通过传入的复选框元素定位:
假设DOM结构是这样:<div class="item"> <input type="checkbox" onclick="pass(this)"> <span class="hello">hello</span> </div>对应的
pass函数可以这么写:function pass(checkbox) { // 获取复选框的下一个兄弟元素(即目标hello元素) const helloEl = checkbox.nextElementSibling; // 直接操作样式,比如选中时变红色 helloEl.style.color = checkbox.checked ? '#ff0000' : '#000000'; }如果元素不是直接相邻,也可以通过父容器查找:
const helloEl = checkbox.parentElement.querySelector('.hello');用自定义属性绑定元素标识
给复选框加一个自定义属性(比如data-target),把对应hello元素的ID写进去,实现精准定位:<input type="checkbox" onclick="pass(this)" data-target="hello_01"> <span id="hello_01" class="hello">hello</span>函数里通过ID获取元素:
function pass(checkbox) { const targetId = checkbox.dataset.target; const helloEl = document.getElementById(targetId); if (helloEl) { // 比如选中时添加下划线 helloEl.style.textDecoration = checkbox.checked ? 'underline' : 'none'; } }事件委托(批量处理多组元素)
如果页面上有很多组复选框和hello元素,用事件委托更高效,不用给每个复选框单独绑定事件:<div id="group-container"> <div class="item"> <input type="checkbox"> <span class="hello">hello 1</span> </div> <div class="item"> <input type="checkbox"> <span class="hello">hello 2</span> </div> </div>绑定事件到父容器:
document.getElementById('group-container').addEventListener('change', function(e) { // 判断触发事件的是复选框 if (e.target.type === 'checkbox') { const helloEl = e.target.nextElementSibling; // 操作样式,比如选中时字体变粗 helloEl.style.fontWeight = e.target.checked ? '700' : '400'; } });
内容的提问来源于stack exchange,提问作者Saarthak Gupta
相关产品推荐
相关产品推荐

