如何使用选定的组合框项目作为变量来使用 javascript 图像调用?
HTML
<select id="fileType">
<option value=".jpg">.JPG</option>
<option value=".png">.PNG</option>
<option value=".gif">.GIF</option>
</select>
JavaScript
var selectedComb = document.getElementById("fileType");
var selectedFileType = selectedComb.options[selectedComb.selectedIndex];
var selectedType = selectedFileType.value;
document.write('<img src="example.com/images/pic + 'selectedType'"/>');
现在,显然这不起作用。我怎样才能让它发挥作用?实际上只是需要修复 document.write 行。
最佳答案
您应该使用document.write()
在加载文档时动态插入内容。
根据MDN's doc :
Writing to a document that has already loaded without calling
document.open()
will automatically perform adocument.open()
call
来自 document.open()
:
If a document exists in the target, this method clears it
所以,使用 document.write()
加载文档后将覆盖(或清除)您的文档。出于这样的原因,using document.write()
is considered a bad practice .
使用
document.body.innerHTML+= '<img src="example.com/images/pic' +selectedType+ '"/>';
相反会解决问题。
关于javascript - 在 JavaScript 中调用组合框值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26085668/