[英]How can I change the image url of an image based on #var=test variable?
我正在尝试基于#var = 1`(或2、3或4)中的变量更改aspx asp.net c#页面上图像的imageurl
不幸的是,我对javascript一无所知。 谁能指出我一个可以通过实施学习的基于新手的脚本?
您的问题非常含糊,因此我不确定您到底需要什么...我只是要编写一些代码,看看它是否接近标准
尝试类似
<img id="someUniqueIdYouMakeUp">
<script type="text/javascript">
theImage = document.getElementById("someUniqueIdYouMakeUp");
if(window.location.hash == "#var=1")
{
theImage.src = "/some/image.jpg";
}
else if(window.location.hash == "#var=2")
{
theImage.src = "/some/other/image.jpg";
}
</script>
编辑 :根据您的评论,即使页面加载后哈希值发生变化,您仍在寻找要更新的图像。 为此,您将需要类似于以下代码:
var updateImageWhenHashChanges = function()
{
theImage = document.getElementById("someUniqueIdYouMakeUp");
if(window.location.hash == "#var=1")
{
theImage.src = "/some/image.jpg";
}
else if(window.location.hash == "#var=2")
{
theImage.src = "/some/other/image.jpg";
}
// Tell the window to call updateImageWhenHashChanges() again in 500 miliseconds:
window.setTimeout(updateImageWhenHashChanges,500);
}
updateImageWhenHashChanges();
有关更多信息,请阅读有关window.setTimeout的信息 。
不幸的是,答案将和问题一样模糊。
显然,您想知道如何修改图像的src
属性。
在您的HTML中给出此图片:
<img id="myImage" src="someOldValue" />
您可以使用此javascript代码通过其ID获取图像,并更改src属性。
<script type="text/javascript">
document.getElementById('myImage').src="someNewValue";
</script>
只需将脚本放在HTML body
标签的底部即可,它应该可以工作。
请注意,这是一个纯JavaScript解决方案。 如果您要使用jQuery,则根据您的实际情况可能值得采用jQuery方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.