javascript 如何在单击时同时获取图像名称和 src?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15569425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How get both image name and src on single onclick?
提问by Sudha Sarath
Is this possible, get both image name and src on single click of an image?
这是可能的,单击图像即可获得图像名称和 src 吗?
I am new to javascript and php.
我是 javascript 和 php 的新手。
<script language="javascript" type="text/javascript">
function SetImageName(strName)
{
document.getElementById("ImageName").value = strName;
}
</script>
<div id="Images">
<img src="images/image1.jpg" name="image1.jpg" onclick="SetImageName(this.name)"/></a>
<img src="images/image2.jpg" name="image2.jpg" onclick="SetImageName(this.name)"/>
</div><input type="hidden" value="" id="ImageName" name="ImageName"/>
回答by nnnnnn
Is it possible? Of course.
是否可以?当然。
In your html markup:
在您的 html 标记中:
onclick="SetImageName(this)"
And then in your JS:
然后在你的 JS 中:
function SetImageName(imgElement) {
var theName = imgElement.name;
var theSrc = imgElement.src;
// etc.
That is, when you call SetImageName()
pass the reference to the clicked element itself with this
, rather than just its name with this.name
. Then within your function you can access any and all of its properties as needed.
也就是说,当您使用 调用SetImageName()
传递对被单击元素本身的引用时this
,而不仅仅是使用this.name
. 然后在您的函数中,您可以根据需要访问其任何和所有属性。
回答by Dave S
You can get the 'src' of the image using this function:
您可以使用此函数获取图像的“src”:
document.getElementById("imagename").src
So your code would be:
所以你的代码是:
<script language="javascript" type="text/javascript">
function SetImageProperties(control)
{
// Populate hidden fields with properties of the control
document.getElementById("ImageName").value = control.name;
document.getElementById("ImageSource").value = control.src;
}
</script>
<div id="Images">
<img src="images/image1.jpg" name="image1.jpg" onclick="SetImageProperties(this)"/>
<img src="images/image2.jpg" name="image2.jpg" onclick="SetImageProperties(this)"/>
</div><input type="hidden" value="" id="ImageName" name="ImageName"/>
</div><input type="hidden" value="" id="ImageSource" name="ImageSource"/>
By passing
通过传递
this
instead of
代替
this.name
you are passing a reference to the whole DOM object. You can then use each property separately as shown in your modified code above.
您正在传递对整个 DOM 对象的引用。然后,您可以单独使用每个属性,如上面修改后的代码所示。
回答by lolo
When the user will click the image the function SetImageName
will invoked by:
当用户单击图像时,该函数SetImageName
将通过以下方式调用:
onclick="SetImageName(this)"
Meaning:
意义:
<img src="images/image1.jpg" name="image1.jpg" onclick="SetImageName(this)"/>
SetImageName
Function implementation you will get the name and src of the image by image.name
and image.src
SetImageName
函数实现你将通过image.name
和获取图像的名称和源代码image.src