//使用firstChild
//但是下面這種因為有空格,也算其子元素
<lable> <span id="onlinePerson" name="person" onclick="changeImg(this)" > <img id="imgPerson" src="images/invote-checked.png">個人 </span> </lable>
//所以要改成這樣,去掉空格
<lable>
<span id="onlinePerson" name="person" onclick="changeImg(this)" ><img id="imgPerson" src="images/invote-checked.png">個人</span>
</lable>
以上為html, js部分如下,這個是點擊切換圖片的例子
var isClick = false; function changeImg(obj) { invoteOnline.getElementsByTagName("img")[0].src = "images/invote-nochecked.png" if(isClick){ imgPerson.src = "images/invote-checked.png"; imgCompany.src = "images/invote-nochecked.png"; isClick = false }else { imgPerson.src = "images/invote-nochecked.png"; imgCompany.src = "images/invote-checked.png"; isClick = true; } console.log(obj.firstChild); //查找元素的子元素,注意空格 console.log(obj.getAttribute("name"));//獲取name return false; }
效果如下