最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Incorporating a javascript variable in a file path - Stack Overflow

programmeradmin2浏览0评论

I am developing a page to display an image, dependent on what the user has previously chosen from a menu. The name of the .jpg is passed in as a parameter ('photo') on the URL and I have been able to parse this as a global variable (myphoto). The .jpgs are all held in one folder.

I now need to do something like (I guess) quoting the image source as being

"myfolder/"+<script>document.write(myphoto)</script> 

but this is not working. Any ideas please?

(Image tag changed here to get round the anti-spam.)

BTW all client-side javascript. It's been a few years since I've used this!

I am developing a page to display an image, dependent on what the user has previously chosen from a menu. The name of the .jpg is passed in as a parameter ('photo') on the URL and I have been able to parse this as a global variable (myphoto). The .jpgs are all held in one folder.

I now need to do something like (I guess) quoting the image source as being

"myfolder/"+<script>document.write(myphoto)</script> 

but this is not working. Any ideas please?

(Image tag changed here to get round the anti-spam.)

BTW all client-side javascript. It's been a few years since I've used this!

Share Improve this question edited Jul 4, 2010 at 20:49 Oded 500k102 gold badges893 silver badges1k bronze badges asked Jul 4, 2010 at 20:44 LinnetLinnet 11 silver badge2 bronze badges 2
  • What code have you got so far? – Matthew Abbott Commented Jul 4, 2010 at 20:46
  • Just format your code as code (by intending it with four spaces or by using backticks ` ) and it is displayed correctly ;) – Felix Kling Commented Jul 4, 2010 at 20:46
Add a ment  | 

3 Answers 3

Reset to default 2

You can do the opposite and output the whole image tag in javascript:

<script language="javascript">
  document.write('<img src="myfolder/' + myphoto + '" />')'
</script>

It's not working because when the browser sees this line: <img src="myfolder/"+<script>document.write(myphoto)</script>, it's treating the + character as a character and not an operator.

You will need to programmatically set the src of the image. Something like this:

document.getElementById("myImage").src = "myfolder/" + myphoto;

or with jQuery:

$("#myImage").attr("src", "myfolder/" + myphoto);
document.getElementById("imgtagid").src = "your image folder/" + selectedPhoto
发布评论

评论列表(0)

  1. 暂无评论