Javascript从特定图像onclick获取.src [英] Javascript get .src from specific image onclick

查看:319
本文介绍了Javascript从特定图像onclick获取.src的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试进行图像交换(单击较小的图像,它将在屏幕的较大区域更改图像).但是我将变量imgSrc定义为未定义.我相信这是因为我没有获得要单击的特定图像的来源.

I'm trying to make an image swapper (click smaller image and it changes the image in a larger area of the screen). But I am getting the variable imgSrc as undefined. I believe this is because I am not getting the source for the specific image being clicked.

        var imgSrc = document.getElementsByClassName('avatar-small').src;
        console.log("img Src  = " + imgSrc);

HTML :

<img class="avatar-small" onclick="selectAvatar()" src="images/avatars/1.png">
<img class="avatar-small" onclick="selectAvatar()" src="images/avatars/2.png">
<img class="avatar-small" onclick="selectAvatar()" src="images/avatars/3.png">

如何使用.this利用某些东西,以便实际上从所单击的图像中获取源?

How can I make use of something using .this so I am actually getting the source from the image that is clicked?

控制台日志输出:

img Src  = undefined 

寻找JavaScript图像交换器的人的解决方案

脚本:

function selectAvatar(this){
    var imgSrc = element.src;
    document.getElementById("avatar-big").src = imgSrc;
}

HTML:

<img id="avatar-big" src="images/avatars/10.png />

<img class='avatar-small' onclick='selectAvatar(this)' src='images/avatars/1.png' />
<img class='avatar-small' onclick='selectAvatar(this)' src='images/avatars/2.png' />
<img class='avatar-small' onclick='selectAvatar(this)' src='images/avatars/3.png' />

推荐答案

从onClick()调用函数时,您需要将'this'传递给该函数,否则该函数本身未定义'this'并且将默认为"this",引用Window对象.

When you call a function from onClick() you need to pass 'this' to the function, otherwise the function itself doesn't have 'this' defined and will default to 'this' referencing the Window object.

<img src="xxxx.jpg" onclick="myFunction(this)" />

您也不需要按班级搜索.如果这样做,最终将得到所有元素的数组.只需将"this"传递给函数并以这种方式简化即可.

You also don't need to search by class. If you do that you'll end up getting an array of all of the elements. Just pass 'this' to the function and simplify it this way.

function myFunction(element) {
  var thing = element.src;
}

现在,您已经拥有了src,可以根据需要使用它!

Now you've got your src and can do with it as you please!

这篇关于Javascript从特定图像onclick获取.src的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆