[英]JavaScript - img name onclick event
How do I have JavaScript telling me the current image name with an ONCLICK event... and I need to do this with alert() for some reasons. 我如何让JavaScript通过ONCLICK事件告诉我当前图像的名称...,出于某些原因,我需要使用alert()来执行此操作。
function imgName() {
window.alert()
}
HTML HTML
<figure>
<img src="aster.jpg" alt="aster" onclick="window.alert()">
<figcaption><span>I am aster</span></figcaption>
</figure>
Thanks 谢谢
Change: 更改:
onclick="window.alert()"
to: 至:
onclick="imgName(this)"
and within your imgName
function change: 并在您的
imgName
函数中更改:
window.alert()
to 至
alert(foo.src)
where foo
is the argument you pass to the function via function imgName(foo)
其中
foo
是您通过function imgName(foo)
传递给函数的参数
function imgName(foo) { alert(foo.src) }
<figure> <img src="aster.jpg" alt="aster" onclick="imgName(this)"> <figcaption><span>I am aster</span></figcaption> </figure>
Or you could just ditch the function and alert the src directly via: 或者,您可以抛弃该功能并通过以下方式直接向src发出警报:
<figure>
<img src="aster.jpg" alt="aster" onclick="alert(this.src)">
<figcaption><span>I am aster</span></figcaption>
</figure>
Please see below - 请看下面-
<html>
<body>
<script language="javascript" >
function imgName() {
var fullPath = document.getElementById("img1").src;
window.alert(fullPath)
}
</script>
<img src="aster.jpg" alt="aster" id="img1" onClick="imgName()">
</form>
</body>
</html>
In "onclick" you are not calling the function "imgName()". 在“ onclick”中,您没有调用函数“ imgName()”。 Do this:
做这个:
<figure>
<img src="aster.jpg" alt="aster" onclick="imgName()">
<figcaption><span>I am aster</span></figcaption>
</figure>
If "current image name" means that you want the alt attribute ("aster"), the code of function need to be this: 如果“当前图像名称”表示您需要alt属性(“ aster”),则功能代码应为:
function imgName() {
var nameOfPics = document.getElementsByTagName("img")[0].getAttribute("alt");
alert(nameOfPics);
}
Giving an id to image for query from js code. 为图片提供ID以从JS代码进行查询。
and just writing: 并只写:
alert(document.querySelector('#imageId').alt) //supposed alt as name.
The problems is when you click the image, you didn't call the related function. 问题是当您单击图像时,您没有调用相关功能。
Change onclick="window.alert()"
with the related function to return window alert. 使用相关函数更改
onclick="window.alert()"
以返回窗口警报。
<img src="aster.jpg" alt="aster" onclick="window.alert()">
Change with : 更改:
<img src="aster.jpg" alt="aster" onclick="imgName()">
I Hope its can help you, pardon me if this is not the best answer 我希望它能为您提供帮助,如果这不是最佳答案,请原谅
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.