0

I'm trying to get the src of any image through plain JavaScript on mouseover.

// Retrieve image URL.
document.getElementsByTagName('img').onmouseover = getURL();

function getURL() {
    var URL = this.getAttribute('src');
}

I can't bind any of these images to an ID and just getElementById. I have to get any image without modifying the DOM and without jQuery. Looks like getElementsByTagName gets you an array. How would I make this function work? Thanks.

4

2 回答 2

1

.getElementsByTagName()返回一个节点列表,它是类似的数组。您必须将事件处理程序添加到每个图像或使用事件委托

var imgs = document.getElementsByTagName('img')
for(var i = 0; i < imgs.length; i++) {
   imgs[i].onmouseover = getURL;
}
于 2013-11-10T19:59:30.897 回答
0

由于它返回一个数组,因此您必须指定要获取的数组索引。这应该将 onmouseover 函数应用于页面上找到的第一个 img 标签。

// Retrieve image URL.
document.getElementsByTagName('img')[0].onmouseover = getURL;

function getURL() {
    var URL = this.getAttribute('src');
}

并将其应用于页面上的所有图像:

var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++)
{
   images[i].onmouseover = getURL;
}
于 2013-11-10T19:59:17.810 回答