动态 JavaScript 图像 SRC 路径替换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3207950/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:41:03  来源:igfitidea点击:

Dynamic JavaScript Image SRC Path Replacement

javascript

提问by aegenes

I'm trying to use JS to dynamically replace an image on a page based upon the value of the selected option of a select dropdown. Everything in the code I've included below works perfectly. My "selected_text" variable is properly pulling the value of the selected option in my select dropdown, but I need to somehow write that value to the replacement img src path.

我正在尝试使用 JS 根据选择下拉列表的所选选项的值动态替换页面上的图像。我在下面包含的代码中的所有内容都可以完美运行。我的“selected_text”变量在我的选择下拉列表中正确地拉出所选选项的值,但我需要以某种方式将该值写入替换 img src 路径。

IE: If someone selects "Audi" from my select dropdown, I want to write "Audi" where I have "[selected_text]" in my replacement img src path.

IE:如果有人从我的选择下拉列表中选择“奥迪”,我想在我的替换 img src 路径中有“[selected_text]”的地方写上“奥迪”。

Any ideas?

有任何想法吗?

<script type="text/javascript">
function popmake() {
    var w = document.vafForm.make.selectedIndex;
    var selected_text = document.vafForm.make.options[w].text;
    document.getElementById('make-image').src="/path/to/images/[selected_text].jpg";
}
</script>

回答by dalton

what about

关于什么

document.getElementById('make-image').src="/path/to/images/" + selected_text + ".jpg";

回答by JAL

It's simple as string concatenation:

就像字符串连接一样简单:

document.getElementById('make-image').src="/path/to/images/"+selected_text+".jpg";

回答by Francisco Soto

Well, you could have that string somewhere like:

好吧,你可以在某个地方使用该字符串:

var path_to_images = "/path/to/images/[selected_text].jpg";

... code ...

var selected_text = document.vafForm.make.options[w].text;

document.getElementById('make-image').src = path_to_image.replace("[selected_text]", selected_text);