遍历DOM以回传图像

Traverse the DOM to passback an image

本文关键字:图像 DOM 遍历      更新时间:2023-09-26

Ok,那么我想点击图像'。escape'并传回图像的源'。myimg2 onclick。下面是我的尝试:我知道它只是遍历DOM,但我不知道如何遍历DOM。谢谢你的指点。

<table class="table2">
    <tr>
        <td>
            <div class="info2" ondragstart="return false" ondragover="allowDrop(event)" ondrop="drop(event)" >
                <div  style="float:left">
                    <img class="myimg2" style="max-height:80px;" src="Pictures/QuestionMark.png">
                </div>
                <div style="float:left;">
                    <p class="myname2">Name: Unspecified</p>
                    <p class="myprof2">Profession: Unspecified</p>
                </div>
                <img class="escape" onclick="returnDrop(this.parentNode.childNode[0].src)" style="max-height:8px;" src="Pictures/escape.png">
            </div>
        </td>
</tr>
</table>
this.parentNode.getElementsByClassName('myimg2')[0]

演示:http://jsfiddle.net/ENQFX/

您正在谈论id (#escape),但您正在使用类(.escape)。您应该将类属性切换为id,因为它们是惟一的。这里我将使用class。你应该把它放在.escapeonclick=属性中。

this.setAttribute('src',this.parentNode.getElementsByClassName('myimg2')[0].getAttribute('src'))

这里我们将src属性设置为.escape父元素中第一个.myimg2类元素的属性。如果没有其他元素具有.myimg2类,则可以使用document.get...代替this.parentNode.get...

用id代替类:

this.setAttribute('src',document.getElementById('myimg2').getAttribute('src'))

请注意,对于id,您不必指定父节点,因为id在整个文档中对元素是唯一的。