开发者

How can I change the image url of an image based on #var=test variable?

I'm trying to change an image's imageurl on an aspx asp.net c# page based on a variable from #var=1` (or 2, or 3, or 4)

I know nothing about javascript unfortunately which is what I've been told I need开发者_运维技巧. Can anyone point me at a novice based script I can try to learn via implementation?


Your question is very vague so I'm not sure exactly what you need... I'm just going to write some code and see if it's close to the mark

Try something like

<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>

EDIT: Based on your comment, you're looking for the image to update even if the hash changes after the page has loaded. For that, you'll need code similar to the following:

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();

For more information, read about window.setTimeout.


Unfortunately, the answer is going to be as vague as the question.

It seems clear that you want to know how to modify the src attribute of an image.

Given this image in your HTML:

<img id="myImage" src="someOldValue" />

You could use this javascript code to get the image by its ID, and change the src attribute.

<script type="text/javascript">     

    document.getElementById('myImage').src="someNewValue";

</script>

Just place the script at the bottom of your HTML body tag, and it should work.

Please note, that this is a pure javascript solution. If you're going to use jQuery, it may be worth taking a jQuery approach depending upon your actual scenario.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜