假设我有以下代码:
<p>
<label>
<input name="milk" type="checkbox">
<span>Milk</span>
</label>
</p>
如何使用javascript获取span
标签之间的文本?如果登录到控制台,结果应为Milk
。谢谢!
function printText(el) {
console.log( el.parentNode.querySelector('span').innerHTML );
}
<p>
<label>
<input name="milk" type="checkbox" onclick="printText(this)">
<span>Milk</span>
</label>
</p>
[Edit: OP询问是否无法更改HTML如果不能更改HTML,则可以通过如下所示的javascript找到复选框并跨越元素:
var chkBox = document.querySelector('input[type="checkbox"][name="milk"]'); chkBox.addEventListener("click", function() { if(this.checked) { // remove this if statement if you want it to print on every click console.log( this.parentNode.querySelector('span').innerHTML ); } });
<p> <label> <input name="milk" type="checkbox"> <span>Milk</span> </label> </p>